Problem 188604 · easy · Phase 01 Prerequisites & Setup

Shopping Until the Money Runs Out

loops · lists · break · accumulation

You walk down a shop aisle picking up items in order. Their prices are in the list prices and you have budget coins. You buy items one by one until the next item would cost more than you have left, and then you stop (even if a later item would be affordable). Write items_bought(prices, budget) that returns how many items you buy.

Examples

Input:  prices = [4, 3, 5, 2], budget = 10
Output: 2
Explanation: 4 + 3 = 7 fits; adding 5 would make 12, so you stop.

Input:  prices = [], budget = 5
Output: 0

Constraints

  • 0 <= len(prices) <= 10**5
  • 0 <= prices[i] <= 1000
  • 0 <= budget <= 10**9

Goals

  • Stop a loop early when a limit would be exceeded
  • Count how many items were processed before stopping
Starting Python…