Items Within Budget
prices lists the prices of the items on a shelf from left to right, and budget is how much you can spend. You take the items from the left end one after another and stop just before the first item that would push your total spending above budget.
Return how many items you take. Prices are never negative, and an item priced 0 costs nothing. Spending exactly budget is allowed.
Example 1
prices [3,2,4,1]
budget 9
returns 3
3 + 2 + 4 = 9 fits the budget exactly; adding the next item (1) would reach 10.
Example 2
prices [5,1,1]
budget 4
returns 0
The very first item costs more than the budget, so nothing is taken.
Constraints
0 <= len(prices) <= 1000 <= prices[i] <= 10000 <= budget <= 100000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Arrays problems
- Kids With the Most CandiesBeginner
- Largest At Least Twice OthersBeginner
- Longest Increasing RunBeginner
- Max Consecutive OnesBeginner
- Peak So FarBeginner
- Running Sum of an ArrayBeginner
- Second AppearanceBeginner
- Shift Right and FillBeginner