Ctrl K

Most Snacks on a Budget

Medium
A snack machine holds n bars, and prices[i] is the price of the i-th bar in coins. You have budget coins and want to buy as many bars as you can; each bar can be bought at most once. Return how many bars you can buy. The prices are small: try to avoid a comparison sort and use counting instead.
Example 1
prices=[5, 2, 9, 3, 2], budget=10 → 3

Take the cheapest first: 2 + 2 + 3 = 7. The next bar costs 5 with only 3 coins left, so that makes 3 purchases.

Example 2
prices=[12, 15], budget=11 → 0

Even the cheapest bar costs more than the budget, so the answer is 0.

Example 3
prices=[4, 1, 4, 1], budget=10 → 4
Constraints
  • 1 ≤ n = len(prices) ≤ 10⁵
  • 1 ≤ prices[i] ≤ 10⁵
  • 1 ≤ budget ≤ 10⁸
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsOne Rook per Line MediumStrength of the Weaker Partner EasyScooters to Chargers EasyBiggest Number From Pieces MediumStudios for Recording Sessions Medium
loading Python…
Input
prices=[5, 2, 9, 3, 2], budget=10
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 76 tests on the server, hidden ones included.