Sunday, January 25, 2026

[LeetCode] Minimum Cost of Buying Candies With Discount

Problem: 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.

  • For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4.

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.

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.
The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.
Input: cost = [6,5,7,9,2,2]
Output: 23
Explanation: The way in which we can get the minimum cost is described below:
- Buy candies with costs 9 and 7
- Take the candy with cost 6 for free
- We buy candies with costs 5 and 2
- Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.
Input: cost = [5,5]
Output: 10
Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.
Hence, the minimum cost to buy all candies is 5 + 5 = 10.


Approach: The question is to get the minimum cost possible. Given we can exclude the cost of every third candy, we need to exclude the maximum cost candy possible. Given we can only exclude a candy from the triplet if the cost of other two candies are more or equal to the excluded candy. That means we can exclude 3rd maximum, 6th maximum, 9th maximum and so on.

Given we need to exclude the maximum cost candy possible given the above condition, what we can do is to sort the array in descending order and then it becomes simple to exclude cost[2], cost[5], cost[8] and so on. Remaining sum of the array is our answer.


Implementation in C#:

    public int MinimumCost(int[] cost)
    {
        int length = cost?.Length ?? 0;
        if (length == 0)
        {
            return 0;
        }
        Array.Sort(cost, (i, j) => {
            return j.CompareTo(i);
        });
        int minCost = 0;
        for (int i = 1; i <= length; ++i)
        {
            if (i % 3 == 0)
            {
                continue;
            }
            minCost += cost[i - 1];
        }
        return minCost;
    }


Complexity: O(nlogn)

No comments:

Post a Comment