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
kiof 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code