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 Problem Overview123Money: 4Chocolate PricesBudgetPick cheapest pair: 1 + 2 = 3Can afford? 3 ≤ 4 ✓Leftover: 4 - 3 = 1
Understanding the Visualization
1
Input
Array of chocolate prices and available money
2
Find Minimum Pair
Identify the two cheapest chocolates
3
Calculate Leftover
Return money minus cost, or original money if unaffordable
Key Takeaway
🎯 Key Insight: We only need to find the two minimum prices, not sort the entire array
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