Maximum Ice Cream Bars - Problem

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.

Note: The boy can buy the ice cream bars in any order.

Return the maximum number of ice cream bars the boy can buy with coins coins.

You must solve the problem by counting sort.

Input & Output

Example 1 — Basic Case
$ Input: costs = [1,3,2,4,1], coins = 7
Output: 4
💡 Note: Buy ice cream bars at costs [1,1,2,3] for total cost 7. Cannot afford the bar costing 4, so maximum count is 4.
Example 2 — Exact Budget
$ Input: costs = [10,6,8,7,7,8], coins = 5
Output: 0
💡 Note: All ice cream bars cost more than 5 coins, so we cannot buy any. Return 0.
Example 3 — All Affordable
$ Input: costs = [1,6,3,1,2,5], coins = 20
Output: 6
💡 Note: We can afford all ice cream bars: 1+1+2+3+5+6 = 18 ≤ 20. Buy all 6 bars.

Constraints

  • 1 ≤ costs.length ≤ 105
  • 1 ≤ costs[i] ≤ 105
  • 1 ≤ coins ≤ 108

Visualization

Tap to expand
Maximum Ice Cream Bars INPUT $1 $3 $2 $4 $1 costs array: 1 3 2 4 1 Available coins: 7 ALGORITHM STEPS 1 Count Sort Count frequency of prices price: 1 2 3 4 count: 2 1 1 1 2 Sorted Order [1, 1, 2, 3, 4] 3 Greedy Selection Buy cheapest first Buy $1: coins=6, count=1 Buy $1: coins=5, count=2 Buy $2: coins=3, count=3 Buy $3: coins=0, count=4 $4 too expensive! 4 Return Count Total bars bought = 4 FINAL RESULT Ice Creams Purchased: $1 OK $1 OK $2 OK $3 OK $4 X Output: 4 Spent: 1+1+2+3 = 7 coins Remaining: 0 coins Key Insight: Counting sort achieves O(n + max_cost) time complexity, faster than comparison-based sorts for bounded integers. The greedy approach works because buying cheaper items first maximizes the count - no expensive item can provide better value than multiple cheaper ones when the goal is to maximize quantity. TutorialsPoint - Maximum Ice Cream Bars | Greedy + Counting Sort Approach
Asked in
Amazon 15 Google 12 Facebook 8 Microsoft 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen