LeetCode Entry
2144. Minimum Cost of Buying Candies With Discount
Min sum taking 2 out of 3
2144. Minimum Cost of Buying Candies With Discount easy substack youtube
https://dmitrysamoylenko.com/leetcode/

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1377
Problem TLDR
Min sum taking 2 out of 3
Intuition
Sort descending, take greedily
Approach
- if you not sure which way is better forward or backward, you can make min(forward,backward)
Complexity
-
Time complexity: \(O(nlogn)\)
-
Space complexity: \(O(n|1)\)
Code
fun minimumCost(c: IntArray) =
c.sortedDescending().filterIndexed {i,_->i%3<2}.sum()
pub fn minimum_cost(mut c: Vec<i32>) -> i32 {
c.sort_unstable_by(|a, b| b.cmp(a));
c.chunks(3).flat_map(|c| c.iter().take(2)).sum()
}
Comments