Maximum Ice Cream Bars Solution in Python


Problem Description

So, you’ve got a pocket full of coins and a burning desire for ice cream. But wait! The ice cream vendor has a price list that looks like a math exam gone wrong. Each ice cream bar has a different cost, and you want to maximize the number of bars you can buy without going broke. It’s like trying to buy happiness, but instead of therapy sessions, you’re just trying to get your hands on some frozen treats.

In this problem, you are given a list of costs for ice cream bars and a certain number of coins. Your mission, should you choose to accept it, is to determine the maximum number of ice cream bars you can buy without exceeding your coin limit.

Code Solution


class Solution:
    def maxIceCream(self, costs: list[int], coins: int) -> int:
        for i, cost in enumerate(sorted(costs)):
            if coins >= cost:
                coins -= cost
            else:
                return i
        return len(costs)

Approach

The approach taken in this solution is straightforward yet effective. First, we sort the list of ice cream costs in ascending order. This way, we can start buying the cheapest ice cream bars first, maximizing the number of bars we can purchase. We then iterate through the sorted list, checking if we have enough coins to buy each bar. If we can afford it, we deduct the cost from our coins. If we can’t afford the next bar, we simply return the count of bars we’ve bought so far. If we manage to buy all the bars, we return the total number of bars.

Time and Space Complexity

Time Complexity: O(n log n) due to the sorting of the costs, where n is the number of ice cream bars.

Space Complexity: O(1) since we are using a constant amount of space for our variables.

Real-World Example

Imagine you’re at a carnival, and you’ve got $10 to spend. You see a stand selling ice cream bars for $1, $2, and $3. If you buy the $1 bars first, you can get 10 of them! But if you start with the $3 bars, you might only get 3 before you run out of cash. This problem is all about strategy—just like life, where sometimes you have to make tough choices about how to spend your limited resources.

Similar Problems

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