Buy Two Chocolates - Problem

You're on a sweet shopping spree! ๐Ÿซ Given an array prices representing the cost of various chocolates in a store and your initial money, you need to buy exactly two chocolates while staying within budget.

Goal: Minimize the total cost of the two chocolates you buy, ensuring you still have non-negative leftover money.

Return: The amount of money remaining after your purchase. If it's impossible to buy two chocolates without going into debt, return your original money amount unchanged.

Example: If chocolates cost [1, 2, 2] and you have 3 dollars, buy the cheapest two (costs 1 + 2 = 3), leaving you with 0 dollars.

Input & Output

example_1.py โ€” Basic Case
$ Input: prices = [1, 2, 2], money = 3
โ€บ Output: 0
๐Ÿ’ก Note: Buy chocolates costing $1 and $2 (total $3). You have exactly $3, so leftover is $0.
example_2.py โ€” Insufficient Funds
$ Input: prices = [3, 2, 3], money = 3
โ€บ Output: 3
๐Ÿ’ก Note: Cheapest pair costs $2 + $3 = $5, but you only have $3. Cannot buy two chocolates, so return original $3.
example_3.py โ€” Multiple Options
$ Input: prices = [1, 2, 3], money = 5
โ€บ Output: 2
๐Ÿ’ก Note: Optimal pair is $1 + $2 = $3. Even though $1 + $3 = $4 or $2 + $3 = $5 are affordable, we choose minimum cost. Leftover: $5 - $3 = $2.

Constraints

  • 2 โ‰ค prices.length โ‰ค 50
  • 1 โ‰ค prices[i] โ‰ค 100
  • 1 โ‰ค money โ‰ค 100
  • Must buy exactly two chocolates
  • Leftover money must be non-negative

Visualization

Tap to expand
Greedy Chocolate Selection๐Ÿซ Sweet Treats Chocolate Shop ๐ŸซUnsorted Prices$3$1$2$4SORTSorted Prices$1$2$3$4Pick These Two!๐Ÿ’ฐ Budget CheckAvailable Money: $5Minimum Cost: $1 + $2 = $3โœ… Affordable!Leftover: $5 - $3 = $2
Understanding the Visualization
1
Organize
Sort all chocolate prices from cheapest to most expensive
2
Select
Pick the first two chocolates (guaranteed minimum total cost)
3
Validate
Check if we can afford this optimal pair with our budget
4
Purchase
Calculate remaining money or return original amount if unaffordable
Key Takeaway
๐ŸŽฏ Key Insight: When you need exactly two items and want minimum cost, always choose the two cheapest options available - no complex algorithms needed!
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
23.5K Views
Medium Frequency
~8 min Avg. Time
892 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