Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I am trying the problem : 1833. Maximum Ice Cream Bars from Leetcode:
It is a sweltering summer day, and a boy wants to buy some ice cream
bars. At the store, there are n ice cream bars. You are given an array
costs of length n, where costs[i] is the price of the ith ice cream
bar in coins. The boy initially has coins coins to spend, and he wants
to buy as many ice cream bars as possible. Return the maximum number
of ice cream bars the boy can buy with coins coins.
Note: The boy can buy the ice cream bars in any order.
Example 1:
Input: costs = [1,3,2,4,1], coins = 7
Output: 4
Explanation: The boy
can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 +
2 + 1 = 7.
I am using while loop and in the code as follows:
class Solution {
public:
int maxIceCream(vector<int>& costs, int coins) {
long long int count = 0;
sort(costs.begin(), costs.end());
int i = 0;
while(coins > 0 && i < costs.size())
{
count++;
coins -= costs[i];
i++;
}
return coins;
}
};
I get the following error. Can someone please help why I get this? The code works fine with for loop.
Line 12: Char 19: runtime error: signed integer overflow: 1094795588 - -1094795586 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:21:19
The constraints are given as follows:
costs.length == n
1 <= n <= 10^5
1 <= costs[i] <= 10^5
1 <= coins <= 10^8
In the while loop, you should not check if the money is greater than zero, but you should check if buying another ice cream is possible
if you don't do it, you may spend more money than you have
while(coins - costs[i] > 0 && i < costs.size())
it's worth noting that you're returning the amount of coins left, not the amount of ice cream that was purchased
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Question - A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input - The first line contains three positive integers k, n, w (1 ≤ k, w ≤ 1000, 0 ≤ n ≤ 109), the cost of the first banana, initial number of dollars the soldier has and number of bananas he wants.
Output - Output one integer — the amount of dollars that the soldier must borrow from his friend. If he doesn't have to borrow money, output 0.
Test case input - 3 17 4
Test case output - 13
They have only given 1 example test case unfortunately.
CodeForces link - https://codeforces.com/problemset/problem/546/A
My code -
int main()
{
int k,n,w,s;
cin >> k >> n >> w;
for(int i=1;i<=w;i++){
s = s+i*k;
}
cout << s-n; //line 11
return 0;
}
The CodeForces compiler gives output = 543968169.
On line 11, that compiler gives error - 'uninitialized value usage'.
How do I fix this?
You used the value of the variable s without initializing it.
s is non-static local variable, so it is default-initialized and it means no initialization will be performed for int.
Initialize it to proper value before the loop to fix the problem.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I've just started learning C++ and I came across a simple problem but couldn't solve. Help me please,
In geometric progression, b1=2, r=3.
Create recursive function that outputs initial n sequences of progression. n should be input.
Assuming b1 is the initial number and r is the multiplier (ratio?), that would give 2, 6, 18, 54, ....
The pseudo-code for such a beast would be:
def geometric (limit, current, multiplier):
if limit <= 0: return
print(current)
geometric(limit - 1, current * multiplier, multiplier)
def main():
b1 = 2
r = 3
n = input("How many terms? ")
geometric(n, b1, r)
The reason it's pseudo-code is that I tend to prefer for educational questions since people learn a lot more by converting it rather than just being given an answer.
So, in terms of how the recursive function works, you pass it the number of terms remaining along with the current term and the multiplier.
Provided it hasn't reached its base case (number of terms remaining is zero), it prints the current term then recursively calls itself, adjusting the arguments so as to approach the base case.
Once it has reached the base case, it will return (from all recursive levels).
Turning that into C++ is an exercise I'll leave for the reader, but I can provide something similar so you will see the approach taken.
Let's say you wanted to sum all the numbers between 1 and a given number. It has the same features as any recursive solution, including the one posed in your question:
an operation that can be defined in terms of a simpler operation; and
the base case.
In C++, a complete program to do that would be something like:
#include <iostream>
void recurse(int number, int sum) {
// Base case for printing and returning.
if (number <= 0) {
std::cout << "Sum is " << sum << '\n';
return;
}
// Recurse to next level.
recurse(number - 1, sum + number);
}
int main() {
int myNum;
std::cout << "Enter your number: ";
std::cin >> myNum;
recurse(myNum, 0);
}
Some sample runs:
Enter your number: 3
Sum is 6
Enter your number: 4
Sum is 10
Enter your number: 5
Sum is 15
Enter your number: 6
Sum is 21
Enter your number: 100
Sum is 5050
The explanatory text on your specific question, along with the C++ code showing how to do it for a different question, should hopefully be enough for you to work it out.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I saw a problem where we had to find the wage. If the hours are less than 40 we pay regular wage ($100/hr) if there is overtime we give 1.5 times the original pay ($150/hr).
The challenge was to solve it without if-else/loops/or ternary operations.
It was solved like this
int hours = /*some_number*/;
int wage = (100*hours) + (50*(hours-40))*(hours>40);
This code works.
(hours>40) returns 1 if hours is greater than 40 and returns 0 if it is less.
I understand that it is some kind of boolean operation, but how does it work and what is this called exactly.
The right way to do it is straight-forward:
int hours = /*some_number*/;
int wage = 100*hours;
if (hours > 40) wage += 50 * (hours-40);
To squeeze it to a single expression, the example takes advantage of the fact that a boolean is either 1 or 0. So x*some_bool evaluates to either x or 0.
In your case, if (hours > 40) then
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 1 == 50*(hours-40)
otherwise it is 0.
(50*(hours-40))*(hours>40) == (50*(hours-40)) * 0 == 0
In general it is less readable to write code this way. The only valid uses IMO are in advanced algebraic transformations used in cryptography or complexity theory.
Well you basically answered your question. The (hours > 40) returns 1 if hours is greater than 40 and returns 0 otherwise.
Maybe more tricky part is the fact that this boolean result is then converted to int implicitly before being multiplied by overtime payment, but that is out of the scope of the question.
So the whole code could be indeed expanded in this way
int hours = /* something */
int wage = 0;
int overtime = hours - 40;
if (hours > 40) {
wage = 100*hours + 50*overtime;
}
else {
wage = 100*hours
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am new to c++. The problem consists in minimizing the number of coins required to give the exact change I have 25 10 5 and 1 cent coins.
For example if a customer is owed $3.20 the number of coins to give would be 14 (12 of 25 and 2 of 10).
My problem:
A number like 4.20 says you need 22 coins instead of 18. I know the problem is generated when it multiplies change by 100. I get 419 instead of 420.
Here is my code.
int coins = change * 100;
//How many 25 cent coins you need
if (coins >= 25)
{
quarter = coins / 25;
coins = coins % 25;
}
//How many 10 cent coins you need
if (coins >= 10)
{
dimes = coins / 10;
coins = coins % 10;
}
//How many 5 cent coins you need
if (coins >= 5)
{
nickels = coins / 5;
coins = coins % 5;
}
//How many 1 cent coins you need
if (coins >= 1)
{
pennies = coins / 1;
coins = coins % 1;
}
NumCoins = quarter + dimes + nickels + pennies;
printf("%d \n", NumCoins);
Thanks for your help.
#include<iostream>
using namespace std;
int main()
{
int amount = 420;
int coins[] = { 25, 10, 5, 1 };
int ncoins = 0;
for( int i=0 ; i<sizeof(coins)/sizeof(int) ; ++i )
{
ncoins += amount / coins[i];
amount %= coins[i];
}
cout << "You need " << ncoins << " coin(s)." << endl;
}
You need 18 coin(s).
It is easy to track which specific coins are needed in the for loop. I assume the reader can adjust the code as needed to suit their purposes.
From my understanding of the problem my suggestion on how to do this is essentially having two variables. change (This is the change you have in cents.) as well as coins (This is the total number of coins you need to make change.)
Then once you have the change, you keep subtracting the quarters (that is 25), from the change variable until it is less than 25, then you move onto dimes, nickels and finally pennies. At the same time you decrement the change variable, you increment the coins in order to keep track of the minimum number of coins you need. This should be much cleaner and simpler than keeping track of all these other variables.
Some pseudocode could look like this:
declare variables
do loop of change > 25
change = change - 25
coins = coins + 1
do loop of change > 10
...
(keep doing this for dimes, nickels and pennies)
...
display number of coins needed.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
I'm coding a program to calculate the growth of a bacterial colony until certain point.
Given a "X", that will represent the initial number of bacteria. And given a "Y", that will represent the number limit desired of bacteria in the bacterial colony. Return the number of days and hours that the bacterial colony needs for reaching the limit.
The bacterial colony doubles each hour.
Example.1:
Input: 1, 8
Output: 0, 3
Example.2:
Input: 1000 , 1024000
Output:0, 10
Example.3:
Input: 123, 3453546624536
Output: 1, 10
If the hour calculated returns a fractional number, it must be rounded down.
So far I have written this code:
#include <iostream>
using namespace std;
int main(){
long int binitial, blimit, day, counter=0;
float hour;
cin >> binitial;
cin >> blimit;
while(binitial <= blimit){
binitial = binitial * 2;
counter++;
}
day = counter / 24;
cout << day << " ";
hour = (counter % 24) - 0.5;
cout << (int)hour;
return 0;
}
You can remove the loop by observing that the number of hours is Log2(Y/X). To calculate Log2(A) using the standard functions, calculate log(A)/log(2).
You may need to address precision issues when going from doubles to ints, because the calculations will be approximate. The final expression for the hours may look like this:
int hours = (log(Y/X) / log(2)) + 1E-8; // Add a small delta
Going from hours to days/hours is very simple, too:
cout << hours/24 << " " << hours % 24 << endl;
You can use a long int for hour if you do the following:
hour = counter - (day*24); // The total number of hours minus the number of hours that are in each day.
I don't have a compiler in front of me but you can probably also do something like this:
hour = counter % 24; // this will return the remainder when counter is divided by 24.
If blimit is always a multiple of binitial, the solution is simple:
counter%24 will be always an integer, so you don't have to round it.
In case of day days and hour hours, you only have to do is:
hour = counter%24
A note on the method of calculation: you don't need to iterate if you're only doubling each time. You're just looking for a value of n such that 2n gives the right result.
So, note that ngenerations = log2 blimit - log2 binitial
Once you have the number of generations (as a floating-point number) you can just truncate that to an integer number of hours.