Maximum Ice Cream Bars Solution in C++


Problem Description

Ah, the sweet taste of summer! What could be better than a hot day, a pocket full of coins, and an insatiable craving for ice cream? But wait! You’re not a millionaire, and those ice cream bars are priced like they’re made of gold! The problem is simple: given a list of ice cream costs and a limited number of coins, how many ice cream bars can you buy before your wallet screams for mercy?

In the world of LeetCode, this is known as the Maximum Ice Cream Bars problem. You’re tasked with maximizing the number of ice cream bars you can buy without exceeding your budget. It’s like trying to buy happiness, but with a strict budget!

Code Solution

Here’s the C++ solution that will help you scoop up as many ice cream bars as possible:


class Solution {
 public:
  int maxIceCream(vector& costs, int coins) {
    ranges::sort(costs);

    for (int i = 0; i < costs.size(); ++i)
      if (coins >= costs[i])
        coins -= costs[i];
      else
        return i;

    return costs.size();
  }
};

Approach

The approach here is as straightforward as a kid in a candy store. First, we sort the costs of the ice cream bars in ascending order. Then, we iterate through the sorted list, checking if we can afford the current ice cream bar with the coins we have left. If we can, we buy it (subtracting its cost from our coins). If we can’t afford the next bar, we stop and return the number of bars we’ve bought. Simple, right?

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(n log n)
Space Complexity O(1)

Real-World Example

Imagine you’re at a summer fair, and you have $10 to spend on ice cream. The prices are $1, $2, $3, and $5. You want to maximize your ice cream intake. By following the logic in our code, you’d buy the $1, $2, and $3 bars, totaling $6, leaving you with $4. You could then buy the $5 bar, but alas, it’s just out of reach! So, you walk away with three delicious bars instead of one overpriced one.

Similar Problems

If you enjoyed this problem, you might also like these: