Maximum Ice Cream Bars

On a hot day a boy wants to buy ice cream bars. The store has `n` bars, and `costs[i]` is the price of the `i`th bar in coins. He has `coins` coins and may buy the bars in any order. Return the maximum number of ice cream bars he can buy. Solve it with counting sort.

30:00

Maximum Ice Cream Bars
medium
Free written solution
Topics
Companies

On a hot day a boy wants to buy ice cream bars. The store has n bars, and costs[i] is the price of the ith bar in coins. He has coins coins and may buy the bars in any order. Return the maximum number of ice cream bars he can buy. Solve it with counting sort.

Example 1:
Input: {"costs":[1,3,2,4,1],"coins":7}
Output: 4
Constraints:
  • costs.length=n\text{costs.length} = n

  • 1≤n≤1051 \leq n \leq 10^5

  • 1≤costs[i]≤1051 \leq \text{costs}[i] \leq 10^5

  • 1≤coins≤1081 \leq \text{coins} \leq 10^8

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"costs":[1,3,2,4,1],"coins":7}

coins left 7 / 7

bars bought 0

costs

1
3
2
4
1

count[price] buckets (non-empty only)

$1

$2

$3

$4

5 bars and 7 coins. Cheapest first is always best, and prices are small integers, so count how many bars sit at each price instead of sorting.

Variables
VariableValue
coins7
bars0
DepthFunction Call
Stack empty
0/14