
Buy Two Chocolates (easy)
Problem statement
You are in a chocolate shop where each chocolate has a price, as listed in an array prices. With a certain amount of money in your pocket, you aim to purchase exactly two chocolates.
You would like to minimize the combined cost of these chocolates so that you are left with as much money as possible, without going into debt.
Calculate the amount of money you'll have left after making the purchase. If it's not possible to buy two chocolates without overspending, return the original amount of money you had.
Examples
Example 1:
- Input: prices = [2, 5, 3, 9], money = 10
- Expected Output: 5
- Justification: The optimal choice is to buy chocolates priced at 2 and 3, costing a total of 5. Therefore, you're left with 10 - 5 = 5.
Example 2:
- Input: prices = [10, 20, 15, 5, 25, 30, 35, 40], money = 50
- Expected Output: 35
- Justification: The cheapest two chocolates has cost 5 and 10. Purchasing these costs 15 in total. Thus, you are left with 50 - 15 = 35.
Example 3:
- Input: prices = [7, 1, 5, 3], money = 3
- Expected Output: 3
- Justification: It's impossible to buy two chocolates without going into debt, so you keep your original amount of 3.
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory