Program to find maximum ice cream bars in Python

Suppose we have an array costs with n elements, where costs[i] is the price of the ith ice cream bar in coins. We initially have c number coins to spend, and we want to buy as many ice cream bars as possible. We have to find the maximum number of ice cream bars we can buy with c coins.

So, if the input is like costs = [3,1,4,5,2], c = 10, then the output will be 4 because we can buy ice cream bars at indices 1,4,0,2 (after sorting: costs [1,2,3,4]) for a total price of 1 + 2 + 3 + 4 = 10.

Algorithm

To solve this problem, we use a greedy approach ?

  • Sort the costs array in ascending order

  • Initialize counter i = 0

  • While i < size of costs and c >= costs[i], do:

    • c := c − costs[i]

    • i := i + 1

  • Return i (number of ice cream bars bought)

Implementation

Let us see the following implementation to get better understanding ?

def solve(costs, c):
    costs.sort()
    i = 0
    while i < len(costs) and c >= costs[i]:
        c = c - costs[i]
        i = i + 1
    return i

costs = [3, 1, 4, 5, 2]
c = 10
result = solve(costs, c)
print(f"Maximum ice cream bars: {result}")
print(f"Sorted costs: {sorted([3, 1, 4, 5, 2])}")

The output of the above code is ?

Maximum ice cream bars: 4
Sorted costs: [1, 2, 3, 4, 5]

How It Works

The greedy strategy works because buying the cheapest ice cream bars first maximizes the total count. After sorting, we get costs = [1, 2, 3, 4, 5]. We can buy:

  • Ice cream at cost 1: remaining coins = 10 − 1 = 9

  • Ice cream at cost 2: remaining coins = 9 − 2 = 7

  • Ice cream at cost 3: remaining coins = 7 − 3 = 4

  • Ice cream at cost 4: remaining coins = 4 − 4 = 0

  • Cannot buy ice cream at cost 5 (insufficient coins)

Alternative Implementation

Here's a more concise version using a for loop ?

def max_ice_cream_bars(costs, coins):
    costs.sort()
    count = 0
    
    for cost in costs:
        if coins >= cost:
            coins -= cost
            count += 1
        else:
            break
    
    return count

costs = [3, 1, 4, 5, 2]
coins = 10
result = max_ice_cream_bars(costs, coins)
print(f"Maximum ice cream bars: {result}")

The output of the above code is ?

Maximum ice cream bars: 4

Time and Space Complexity

  • Time Complexity: O(n log n) due to sorting

  • Space Complexity: O(1) if we modify the input array, or O(n) for creating a sorted copy

Conclusion

The greedy approach of buying the cheapest ice cream bars first guarantees the maximum count. Sorting the costs array and iterating while we have sufficient coins provides an optimal solution with O(n log n) time complexity.

Updated on: 2026-03-26T14:41:39+05:30

740 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements