Minimum Cost of Buying Candies With Discount — LeetCode 2144 Python Solution
EasyGreedyArraySorting
- Problem
- #2144
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.
Example
- Input
- cost = [1,2,3]
- Output
- 5
- Explanation
- We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
Python solution
Python
class Solution:
def minimumCost(self, cost: List[int]) -> int:
cost.sort(reverse=True)
return sum(cost) - sum(cost[2::3])Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2144. Minimum Cost of Buying Candies With Discount is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2144. Minimum Cost of Buying Candies With Discount?
- LeetCode 2144. Minimum Cost of Buying Candies With Discount is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2144. Minimum Cost of Buying Candies With Discount?
- The Python solution on this page runs in O(n \log n).
- What is the space complexity of LeetCode 2144. Minimum Cost of Buying Candies With Discount?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2144. Minimum Cost of Buying Candies With Discount cover?
- LeetCode 2144. Minimum Cost of Buying Candies With Discount is tagged Greedy, Array and Sorting on LeetCode.