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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code