Buy Two Chocolates (LeetCode 2706): Solution and Explanation
Buy exactly two chocolates without going into debt and with the smallest total price. Return the money left over, or the original money if no pair is affordable.
Intuition
Leftover money is money minus what you spend, so maximizing leftover means minimizing the price of the pair.
The cheapest possible pair is simply the two cheapest bars. If that pair does not fit in the budget, no other pair can.
Sorting finds them, but only the two smallest values matter, so a single pass that keeps the smallest and second smallest price is enough.
When a new price beats the cheapest, the old cheapest slides down to second place. When it only beats the second, it replaces the second.
Approach: Keep the two smallest prices
- Start with
firstandsecondset to a value larger than any price. - For each price
p: ifp < first, setsecond = firstandfirst = p. Otherwise, ifp < second, setsecond = p. - Let
spent = first + second. Returnmoney - spentifspent <= money, else returnmoney.
Step-by-step example
prices = [1,2,2], money = 3
- p = 1: below first (infinity), so first = 1 and second = infinity.
- p = 2: not below 1 but below infinity, so second = 2.
- p = 2: not below 1 or 2. Skip.
- spent = 1 + 2 = 3, which is at most 3, so the leftover is 3 - 3 = 0.
Code: Python, Java, C++
1class Solution:
2 def buyChoco(self, prices: List[int], money: int) -> int:
3 first = second = 10 ** 9
4 for p in prices:
5 if p < first:
6 first, second = p, first
7 elif p < second:
8 second = p
9 spent = first + second
10 return money - spent if spent <= money else money1class Solution {
2 public int buyChoco(int[] prices, int money) {
3 int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
4 for (int p : prices) {
5 if (p < first) {
6 second = first;
7 first = p;
8 } else if (p < second) {
9 second = p;
10 }
11 }
12 int spent = first + second;
13 return spent <= money ? money - spent : money;
14 }
15}1class Solution {
2public:
3 int buyChoco(vector<int>& prices, int money) {
4 int first = INT_MAX, second = INT_MAX;
5 for (int p : prices) {
6 if (p < first) {
7 second = first;
8 first = p;
9 } else if (p < second) {
10 second = p;
11 }
12 }
13 int spent = first + second;
14 return spent <= money ? money - spent : money;
15 }
16};Time and space complexity
O(n)
One pass with two comparisons per price.
O(1)
Only two running minimums are stored.
Other approaches
Sort (time O(n log n), space O(1))
Sort the prices and use prices[0] + prices[1]. Shorter to write, but O(n log n) and it reorders the input.
Check every pair (time O(n^2), space O(1))
Try all pairs i < j and keep the cheapest affordable one. Fine for 50 bars, but quadratic and unnecessary.
Common mistakes
- Returning a negative number when the cheapest pair costs more than money. The problem asks for money unchanged in that case.
- Overwriting first before copying it into second. The old minimum has to slide down to second, or it is lost.
- Assuming two bars with the same price cannot both be bought. Duplicates are separate bars, as in [1,2,2].
Frequently asked questions
Why is buying the two cheapest bars always right?
Any pair costs at least the sum of the two smallest prices. If that sum fits, it leaves the most money; if it does not fit, nothing does.
Can the starting value of first and second overflow?
Not here. There are at least two prices, so both are replaced by real prices before they are added. In typed languages the maximum int is still safe because it is never summed.
Is leftover money of zero allowed?
Yes. The leftover only has to be non-negative, so spending exactly all of your money is fine.