Choose the two cheapest chocolates you can afford and return the money left over, or keep the original amount if no valid pair exists.
You are given an array of chocolate prices and an amount of money. You want to buy exactly two different chocolates such that the total cost does not exceed your money.
Return the amount of money left after buying the two chocolates with the smallest possible total price that is still affordable. If no pair of chocolates can be bought, return the original amount of money.
The two chocolates must be distinct items from the array.
Input Format
- An integer array
prices, whereprices[i]is the price of the -th chocolate. - An integer
money, the amount you can spend.
Output Format
- Return the remaining money after buying two distinct chocolates with minimum total cost among all affordable pairs.
- If no valid pair exists, return
money.
Constraints
- Choose exactly two distinct chocolates.
- The sum of chosen prices must be less than or equal to
money. - If multiple pairs are affordable, prefer the one with the smallest total price.
- If no pair is affordable, return
money.
Example 1
Input
prices = [1, 2, 2], money = 3
Output
0
Explanation
The two cheapest chocolates cost 1 and 2, which exactly matches the budget. The remaining money is 0.
Example 2
Input
prices = [3, 2, 3], money = 3
Output
3
Explanation
No pair of chocolates can be bought because the cheapest two cost 2 + 3 = 5, which exceeds the budget.
Show 1 more example
Example 3
Input
prices = [3, 1, 2], money = 6
Output
3
Explanation
Buy the two cheapest chocolates, 1 and 2. The remaining money is 6 - 3 = 3.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.