Skip to main content
Back to problems
#2144
Easy Algorithms

Minimum cost of buying candies with discount

Array Greedy Sorting
62.7% acceptance
Feb 25, 2026
688
25
A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free. The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought. Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_cost(cost: Vec<i32>) -> i32 {
    let mut cost = cost;
    cost.sort_unstable_by(|a, b| b.cmp(a)); // descending
    // Every 3rd item (index 2, 5, 8, ...) is free
    cost.iter()
      .enumerate()
      .filter(|(i, _)| (i + 1) % 3 != 0)
      .map(|(_, &c)| c)
      .sum()
  }
}