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.
Examples
Example 1
|
|
Example 2
|
|
Constraints
2 <= prices.length <= 50
1 <= prices[i] <= 100
1 <= money <= 100
Solution
Method 1 – Sorting and Greedy
Intuition
To buy two chocolates and minimize the sum, pick the two cheapest prices. If their sum is less than or equal to money, return the leftover; otherwise, return money.
Approach
- Sort the prices.
- If the sum of the two smallest prices is less than or equal to money, return money minus that sum.
- Otherwise, return money.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
- 🧺 Space complexity:
O(1)