LeetCode Entry

2144. Minimum Cost of Buying Candies With Discount

01.06.2026 easy 2026 kotlin rust

Min sum taking 2 out of 3

2144. Minimum Cost of Buying Candies With Discount easy substack youtube

https://dmitrysamoylenko.com/leetcode/

01.06.2026.webp

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