Buy Two Chocolates - Problem

You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money.

You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.

Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

Input & Output

Example 1 — Basic Case
$ Input: prices = [1,2,3], money = 4
Output: 1
💡 Note: The two cheapest chocolates cost 1 + 2 = 3, which is affordable. Leftover money: 4 - 3 = 1
Example 2 — Cannot Afford Any Pair
$ Input: prices = [3,2,3], money = 3
Output: 3
💡 Note: The cheapest pair costs 2 + 3 = 5, which exceeds our budget of 3. Return original money: 3
Example 3 — Exact Budget Match
$ Input: prices = [1,3,2], money = 3
Output: 0
💡 Note: Cheapest pair costs 1 + 2 = 3, exactly our budget. Leftover: 3 - 3 = 0

Constraints

  • 2 ≤ prices.length ≤ 50
  • 1 ≤ prices[i] ≤ 100
  • 1 ≤ money ≤ 100

Visualization

Tap to expand
Buy Two Chocolates - One Pass Solution INPUT prices array: $1 choco $2 choco $3 choco [0] [1] [2] Available Money: $4 prices = [1, 2, 3] money = 4 Buy exactly 2 chocolates ALGORITHM STEPS 1 Initialize Minimums min1 = INF, min2 = INF 2 Scan Array Once Track two smallest prices p=1: min1=1, min2=INF p=2: min1=1, min2=2 p=3: min1=1, min2=2 Final: min1=1, min2=2 3 Calculate Sum sum = 1 + 2 = 3 4 Check Affordability 3 <= 4? Yes! Return: 4 - 3 = 1 FINAL RESULT Selected Chocolates: $1 BOUGHT $2 BOUGHT Initial Money: $4 Total Cost: $1 + $2 = $3 Leftover: $4 - $3 = $1 OUTPUT 1 OK - Can Afford! Key Insight: To minimize the sum of two chocolates, we need the two cheapest ones. Instead of sorting O(n log n), we track min1 and min2 in ONE PASS O(n). When we find a smaller price, we update min2 = min1, then min1 = new price. If price is between min1 and min2, only update min2. Time: O(n), Space: O(1) TutorialsPoint - Buy Two Chocolates | One Pass - Find Two Minimums
Asked in
LeetCode 15 Meta 8
12.5K Views
Medium Frequency
~15 min Avg. Time
432 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen