c++sortingwhile-loopgreedy

Getting a signed integer overflow on a Leetcode problem


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

Solution

  • 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