Running Total With Threshold Stop

Medium ⏱ 12 min 52% acceptance ★★★★★ 4.5
Write a function items_until_budget(prices, budget) that iterates through prices in order, adding each price to a running total, and stops (using break) as soon as adding the next price would exceed the budget. Return the list of prices that were actually added (the ones that fit).

Examples

Example 1
Input
items_until_budget([10, 20, 15, 30], 40)
Output
[10, 20]
Explanation

10+20=30 fits; adding 15 would make 45, exceeding 40, so it stops there.

Example 2
Input
items_until_budget([5, 5, 5], 100)
Output
[5, 5, 5]
Explanation

All items fit comfortably within the budget.

Constraints

  • prices is a list of non-negative numbers.
  • budget is a non-negative number.

Topics

Loopswhile loopbreak

Companies

JPMorgan ChaseGoldman Sachs

Hints

Hint 1

Check whether `running_total + price > budget` before adding, and break if so.

Hint 2

Only append the price to the result after confirming it fits.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.