LeetCode 2144: Minimum Cost of Buying Candies With Discount Solution

Master LeetCode problem 2144 (Minimum Cost of Buying Candies With Discount), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2144. Minimum Cost of Buying Candies With Discount

Problem Explanation

Explanation:

To solve this problem, we can sort the given array of candy costs in descending order. Then, we can iterate through the sorted array, keeping track of the running total cost and adding the cost of each candy until we reach a point where we can get a candy for free. We then subtract the cost of the free candy from the running total. Solution:

Solution Code

import java.util.Arrays;

class Solution {
    public int minCost(int[] cost) {
        Arrays.sort(cost);
        int n = cost.length;
        int totalCost = 0;
        
        for (int i = n - 1; i >= 0; i -= 3) {
            totalCost += cost[i];
            if (i - 1 >= 0) {
                totalCost += cost[i - 1];
            }
        }
        
        return totalCost;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2144 (Minimum Cost of Buying Candies With Discount)?

This page provides optimized solutions for LeetCode problem 2144 (Minimum Cost of Buying Candies With Discount) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2144 (Minimum Cost of Buying Candies With Discount)?

The time complexity for LeetCode 2144 (Minimum Cost of Buying Candies With Discount) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2144 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2144 in Java, C++, or Python.

Back to LeetCode Solutions