#2706
Buy Two Chocolates
pupil · 305 · lc easy +21 · verified · 68.3% accepted · 1,069 likes · top 75%
Description
You have money dollars and a prices array of chocolate costs. Buy exactly two chocolates at minimum combined cost while keeping your remaining money non-negative. Return the leftover money, or money unchanged if no valid pair can be purchased.
Example 1:
Input: prices = [1,2,2], money = 3
Output: 0
Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.
Example 2:
Input: prices = [3,2,3], money = 3
Output: 3
Explanation: You cannot buy 2 chocolates without going in debt, so we return 3.
Code
1
2
3