Problem · Array
Spend it All
Learn this problemProblem statement
There is a budget and an array of n costs. Repeat the following process until budget is less than the minimum element in cost.
Process
Start at element 0 and work to n - 1.
At each element cost[i]:
cost[i] <= budget, reduce budget by cost[i] and move to the next index. This is a purchase.cost[i] > budget, move to the next index.
The array is circular, so the next index after n - 1 is index 0.
Continue until there is not enough budget to make a purchase.
Determine how many purchases are made.
Function
countPurchases(cost: int[], budget: long) → int
Complete the function countPurchases in the editor below.
countPurchases has the following parameters:
int cost[n]: the costs of all the itemslong budget: the starting amount of the budget to be spentReturns
long: the number of purchasesExamples
Example 1
cost = [5, 8, 3]budget = 12return = 3Process:
Buy item 0 for 5 -> budget = 12 - 5 = 7.
Item 1 is too expensive, budget = 7.
Buy item 2 for 3, budget = 7 - 3 = 4.
Items 0 and 1 are too expensive, budget = 4.
Buy item 2 for 3, budget = 4 - 3 = 1.
Now budget = 1, and there are no more items that can be purchased.
Return 3, the number of items purchased.
Constraints
More Tiktok problems
- Count Access Code PairsOA · Seen Jul 2026
- Count Key ChangesOA · Seen Jul 2026
- Travel Distance on ScootersOA · Seen Jul 2026
- Count Skipped Numbers After SubtractionsOA · Seen Jul 2026
- Obstacle Placement QueriesOA · Seen Jul 2026
- Repeated Grouped Digit SumOA · Seen Jul 2026
- Count Cyclic Digit PairsOA · Seen Jun 2026
- Event ID Check Completion TimesOA · Seen Jun 2026