Buy Two Chocolates (LeetCode 2706): Solution and Explanation

Easy
Array
Greedy
Sorting

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

  1. Start with first and second set to a value larger than any price.
  2. For each price p: if p < first, set second = first and first = p. Otherwise, if p < second, set second = p.
  3. Let spent = first + second. Return money - spent if spent <= money, else return money.

Step-by-step example

prices = [1,2,2], money = 3
  1. p = 1: below first (infinity), so first = 1 and second = infinity.
  2. p = 2: not below 1 but below infinity, so second = 2.
  3. p = 2: not below 1 or 2. Skip.
  4. 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 money
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass with two comparisons per price.

Space

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.