Remove items so any k prices stay under a threshold
I was asked this
No reports yet. Sign in to say where you were asked it.
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, wheren = len(prices) 1 <= prices[i] <= 10^91 <= 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
kitems remain, is the condition met automatically (so removingn - k + 1items always works)? - Can prices repeat, and does it matter which copy is removed?
- Is only the count returned, or also the items removed?
- Is
thresholdcompared with<=(a group summing exactly tothresholdis fine)?
What a strong answer covers
- Sees that the worst group is always the
kmost expensive remaining items, and that removing the most expensive item first is never worse, so the kept items are the cheapestn - r. - Sorts the prices; for each candidate
r, checks the sum of theklargest among the cheapestn - r, which is a window of the sorted array. - Finds the smallest
rwith a sliding window over the sorted prices (or binary search onrwith 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
kitems stay over a minimum instead.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
