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 ProblemInput: costs = [1,3,2,4,1], coins = 7Ice Cream Costs[1,3,2,4,1]Available: 7 coinsGreedy StrategySort: [1,1,2,3,4]Buy cheapest firstResult4ice cream barsPurchase Details:11234Total cost: 1+1+2+3 = 7 coins ✓Cannot afford (need 4 more)
Understanding the Visualization
1
Input
Array of ice cream costs and available coins
2
Sort & Select
Sort costs and buy cheapest items first
3
Output
Maximum number of ice cream bars purchased
Key Takeaway
🎯 Key Insight: Greedy approach works because buying cheaper items first always maximizes the total count within budget
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