883. Minimum Relative Loss After Buying Chocolates
You are given an integer array prices representing the prices of chocolates available in a store and a 2D integer array queries where each query is of the form [ki, mi].
Alice and Bob visit the store to purchase chocolates. Alice proposes a payment strategy which Bob agrees to. The rules for payment for each chocolate are as follows:
- If the prices[i] <= ki : Bob pays the entire price.
- If the prices[i] > ki : Bob pays exactly ki while Alice covers the remaining cost (price - ki).
For each query [ki, mi], Bob must choose exactly mi chocolates such that his relative loss is minimized. Here, the relative loss is defined as the difference between the total amount Bob pays (denoted as bi) and the total amount Alice pays (denoted as ai), i.e., bi − ai.
Return an integer array ans where ans[i] is the minimum relative loss possible for the query queries[i].
Example 1:
Input : prices = [2, 8, 15, 12, 6], queries = [[10, 3]]
Output : [13]
Explanation :
For the query [10, 3], one optimal selection is [2, 15, 6].
- For the chocolate priced 2 (≤ 10), Bob pays 2.
- For the chocolate priced 15 (> 10), Bob pays 10 while Alice pays 15 − 10 = 5.
- For the chocolate priced 6 (≤ 10), Bob pays 6.
- Thus, Bob’s total payment is 2 + 10 + 6 = 18 and Alice pays 0 + 5 + 0 = 5, so the relative loss is 18 − 5 = 13.
Example 2:
Input : prices = [5, 9, 3, 7], queries = [[7, 2]]
Output : [8]
Explanation :
For the query [7, 2], one optimal selection is [3, 5].
- For the chocolate priced 3 (≤ 7), Bob pays 3.
- For the chocolate priced 5 (≤ 7), Bob pays 5.
- Thus, Bob’s total payment is 3 + 5 = 8 and Alice pays 0, resulting in a relative loss of 8 − 0 = 8.
Now Your Turn!
Pick the correct output for the given inputInput : prices = [4, 13, 8, 10], queries = [[8, 3]]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= prices.length == n <= 105
- 1 <= prices[i] <= 105
- 1 <= queries.length <= 105
- queries[i].length == 2
- 1 <= ki <= 109
- 1 <= mi <= n