← Questions

Remove items so any k prices stay under a threshold

0
AmazonCoding

A coding interview question asked at Amazon. It tests greedy, sorting and sliding window.

A store is planning a holiday promotion from a list of candidate items with known prices. Shoppers may pick any k items from whatever stays on the list, and the store wants every such group of k items to cost at most threshold in total.

Implement:

def reduce_gifts(prices: list[int], k: int, threshold: int) -> int

Return the minimum number of items to remove from prices so that the sum of any k remaining items is at most threshold. If fewer than k items remain, no group of k exists and the condition is satisfied.

Constraints

  • 1 <= k <= n <= 10^5, where n = len(prices)
  • 1 <= prices[i] <= 10^9
  • 1 <= threshold <= 10^9

Example 1

prices = [8, 1, 5, 7, 2], k = 2, threshold = 9  ->  2

The most expensive pair is 8 + 7 = 15. Remove 8: the most expensive pair is now 7 + 5 = 12. Remove 7: the most expensive pair is 5 + 2 = 7, which fits. Two removals.

Example 2

prices = [10, 10, 10, 10], k = 1, threshold = 9  ->  4

Every single item is over the limit, so all four must go.

Clarifying questions

  • If fewer than k items remain, is the condition met automatically (so removing n - k + 1 items always works)?
  • Can prices repeat, and does it matter which copy is removed?
  • Is only the count returned, or also the items removed?
  • Is threshold compared with <= (a group summing exactly to threshold is fine)?

What a strong answer covers

  • Sees that the worst group is always the k most expensive remaining items, and that removing the most expensive item first is never worse, so the kept items are the cheapest n - r.
  • Sorts the prices; for each candidate r, checks the sum of the k largest among the cheapest n - r, which is a window of the sorted array.
  • Finds the smallest r with a sliding window over the sorted prices (or binary search on r with prefix sums): O(n log n) for the sort.
  • Uses 64-bit sums (up to 10^5 * 10^9).
  • Tests both examples, k = 1, k = n, and a case where nothing needs removing.

Follow-ups

  • Return the items to remove, not just the count.
  • Prices change or items are added over time.
  • The condition is that the cheapest k items stay over a minimum instead.

Where it's asked

What it tests

greedy · sorting · sliding window

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding