Budget Shopping from Array Suffix
Greedy & IntervalsAuto-graded · 22 test casesLast updated
Tests greedy selection with precomputation, prefix sums, and binary search to maximize item counts under budget constraints.
You are given an array prices where each element represents the cost of an item in a store.
You will process multiple independent queries. Each query is represented by a pair [position, funds]:
- You may only buy items whose index is greater than or equal to
position - You can select any subset of these eligible items (not necessarily consecutive)
- Each eligible item may be purchased at most once
- The total cost of all selected items must not exceed
funds
Your goal is to determine the maximum number of items you can purchase for each query.
Write a function that returns an array where each element is the answer to the corresponding query.
Constraints
1 <= len(prices) <= 10001 <= len(queries) <= 10000 <= position < len(prices)1 <= prices[i] <= 10^91 <= funds <= 10^14
Examples
Example 1
Input: budget_shopping([5, 2, 8, 1, 3], [[0, 7], [2, 4], [3, 10]])
Output: [3, 2, 2]
Example 2
Input: budget_shopping([10, 20, 30], [[1, 5], [0, 60]])
Output: [0, 3]
Hints
Hint 1
Since you want to maximize the count of items, what's the best strategy for selecting which items to buy?
Hint 2
For items starting at a given index, sorting them by price lets you greedily pick the cheapest ones first.
Hint 3
There are only n possible starting positions. Can you precompute something to avoid re-sorting for every query?
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is that to maximize the number of items purchased, we should always choose the cheapest available items first. This greedy strategy is optimal because:
- If we can afford
kitems using any selection, we can definitely afford thekcheapest items - By taking the cheapest items, we leave the most budget remaining for additional purchases
- Item identity doesn't matter, only price
Since there are only n distinct starting positions, we can precompute the answer structure for each suffix of the array:
- Build suffix data from right to left: Starting from the last index and moving backward, maintain a growing collection of items representing each suffix
- Sort and compute prefix sums: For each suffix, sort the prices and build a cumulative sum array where entry
krepresents the total cost of thekcheapest items - Answer queries with binary search: For a query with budget
funds, find the largestksuch that the cost of thekcheapest items does not exceedfunds. Since the cumulative array is strictly increasing (all prices are positive), we can use binary search
The greedy choice is provably optimal: if an optimal solution of k items doesn't use the k cheapest, we could swap any expensive item for a cheaper unused one without exceeding the budget, contradicting the assumption that we couldn't buy more items.
Complexity
- Time:
O(n² log n)for precomputation (sorting each ofnsuffixes) plusO(q log n)for answering queries via binary search - Space:
O(n²)to store the cumulative sum arrays for all suffixes
With n = 1000, the space requirement is manageable (roughly 500,000 integers), and the time complexity remains efficient.
Solution
from bisect import bisect_right
from typing import List
def budget_shopping(prices: List[int], queries: List[List[int]]) -> List[int]:
n = len(prices)
suffix_data = [None] * n
accumulated = []
for pos in range(n - 1, -1, -1):
accumulated.append(prices[pos])
sorted_items = sorted(accumulated)
cumulative = [0]
for cost in sorted_items:
cumulative.append(cumulative[-1] + cost)
suffix_data[pos] = cumulative
answers = []
for position, funds in queries:
cumulative = suffix_data[position]
count = bisect_right(cumulative, funds) - 1
answers.append(count)
return answers