#2706
Buy Two Chocolates
EasyArrayGreedySortingGreedySorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
By sorting the prices first, we can easily find the two cheapest chocolates and check if we can afford them. This significantly reduces the number of checks we need to perform.
⚙️
Algorithm
3 steps- 1Step 1: Sort the prices array.
- 2Step 2: Check if the sum of the first two elements (cheapest chocolates) is less than or equal to money.
- 3Step 3: If yes, return the leftover money after buying them. If no, return the initial money.
solution.py5 lines
1def buyChocolates(prices, money):
2 prices.sort()
3 if prices[0] + prices[1] <= money:
4 return money - (prices[0] + prices[1])
5 return moneyℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, which is more efficient than the O(n²) brute force approach. The space complexity is O(1) since we are not using any additional data structures.
- 1Sorting helps in quickly finding the cheapest options.
- 2Always check if you can afford the cheapest two before proceeding.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.