#1833
Maximum Ice Cream Bars
MediumArrayGreedySortingCounting SortGreedySortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach uses sorting and a greedy algorithm to ensure we buy the cheapest ice cream bars first, maximizing the number we can buy within the budget.
⚙️
Algorithm
3 steps- 1Step 1: Sort the costs array in ascending order.
- 2Step 2: Initialize a count of ice cream bars and a total cost variable.
- 3Step 3: Iterate through the sorted costs, adding the cost of each bar to the total until the total exceeds the available coins.
solution.py13 lines
1# Full working Python code
2
3def maxIceCream(costs, coins):
4 costs.sort()
5 count = 0
6 total_cost = 0
7 for cost in costs:
8 if total_cost + cost <= coins:
9 total_cost += cost
10 count += 1
11 else:
12 break
13 return countℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, which is much more efficient than the brute force approach.
- 1Buying cheaper items first maximizes quantity.
- 2Sorting helps in efficiently managing budget.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.