KatInterview

Budget Shopping from Array Suffix

Greedy & IntervalsAuto-graded · 22 test cases
EasyAuto-gradedGreedy & Intervalsgreedybinary-searchprefix-sum

Last 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) <= 1000
  • 1 <= len(queries) <= 1000
  • 0 <= position < len(prices)
  • 1 <= prices[i] <= 10^9
  • 1 <= 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?