Minimum Cost of Buying Candies With Discount - Complete Solution Guide
Minimum Cost of Buying Candies With Discount is LeetCode problem 2144, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 arra
Detailed Explanation
The problem asks you to determine the minimum cost to buy all candies given a list of candy prices. The twist is that for every two candies purchased, a third candy (the cheapest among the two purchased and remaining candies) is given for free. The input is a 0-indexed integer array `cost` where `cost[i]` represents the price of the i-th candy. The output is a single integer representing the minimum total cost to acquire all candies.
Solution Approach
The solution utilizes a greedy strategy combined with sorting. The candies are first sorted in descending order of price. Then, the algorithm iterates through the sorted array, picking the first two candies in each group of three as paid items and considering the third as free. This process minimizes the total cost by always choosing the most expensive candies to purchase.
Step-by-Step Algorithm
- Step 1: Sort the `cost` array in descending order.
- Step 2: Iterate through the sorted array with a step of 3 (i.e., 0, 3, 6...).
- Step 3: For each iteration, add the cost of the current candy (`cost[i]`) and the next candy (`cost[i+1]`, if it exists) to the `totalCost`.
- Step 4: After the loop, return `totalCost`.
Key Insights
- Insight 1: Sorting the candies in descending order allows us to efficiently pick the most expensive candies first, ensuring we get the maximum discount.
- Insight 2: A greedy approach works optimally here. By always selecting the most expensive candies to pay for and getting the cheapest as a freebie, we minimize the overall cost.
- Insight 3: Handling the edge case of having fewer than 3 candies requires handling the remainder after grouping the candies in sets of 3.
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(1)
Topics
This problem involves: Array, Greedy, Sorting.
Companies
Asked at: Garmin, Nokia.