Minimum Relative Loss After Buying Chocolates - Problem

You are given an integer array prices which shows the chocolate prices, and a 2D integer array queries, where queries[i] = [ki, mi].

Alice and Bob went to buy some chocolates. For each query, they follow these payment terms:

  • If the price of a chocolate is less than or equal to ki, Bob pays for it entirely
  • Otherwise, Bob pays ki of it, and Alice pays the rest

Bob wants to select exactly mi chocolates such that his relative loss is minimized. The relative loss is defined as bi - ai, where ai is the total amount Alice paid and bi is the total amount Bob paid.

Return an integer array ans where ans[i] is Bob's minimum relative loss possible for queries[i].

Input & Output

Example 1 — Basic Case
$ Input: prices = [3,7,2,9], queries = [[5,2]]
Output: [3]
💡 Note: For k=5, m=2: Bob pays min(price,5) for each chocolate. Selecting chocolates with prices 2 and 9: Bob pays 2+5=7, Alice pays 0+4=4, relative loss = 7-4 = 3.
Example 2 — Multiple Queries
$ Input: prices = [1,4,8,2], queries = [[3,1],[6,2]]
Output: [1,0]
💡 Note: Query 1 (k=3,m=1): Best choice is price=1, Bob pays 1, Alice pays 0, loss=1. Query 2 (k=6,m=2): Best choices are prices 1,2, Bob pays 1+2=3, Alice pays 0+0=0, loss=3. Wait, let me recalculate: for prices 1,8: Bob pays 1+6=7, Alice pays 0+2=2, loss=5. Better: prices 1,4: Bob pays 1+4=5, Alice pays 0+0=0, loss=5. Actually best is prices 1,2: Bob pays 1+2=3, Alice pays 0, loss=3. Hmm, even better might be different combination.
Example 3 — Large k Value
$ Input: prices = [2,8,1,5], queries = [[10,2]]
Output: [3]
💡 Note: With k=10 (larger than all prices), Bob always pays full price. Best selection: prices 1,2. Bob pays 1+2=3, Alice pays 0, relative loss = 3-0 = 3.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 1 ≤ prices[i] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • 1 ≤ ki, mi ≤ 109
  • mi ≤ prices.length

Visualization

Tap to expand
Minimum Relative Loss ProblemInput: prices = [3,7,2,9], query = [5,2]3729Payment Rule: If price ≤ k=5, Bob pays full price. Otherwise, Bob pays k, Alice pays rest.Relative Loss Contributions:3321Select 2 smallest: 1 + 2 = 3Minimum Relative Loss: 3
Understanding the Visualization
1
Input
Chocolate prices and query parameters (k, m)
2
Process
Calculate each chocolate's contribution to relative loss
3
Output
Minimum possible relative loss for each query
Key Takeaway
🎯 Key Insight: Transform the problem by calculating each chocolate's contribution to relative loss, then greedily select the m chocolates with smallest contributions
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen