Leetcode 2144: Minimum Cost of Buying Candies With Discount

grid47
grid47
Exploring patterns and algorithms
Apr 6, 2024 5 min read

A shop offers a special deal: for every two candies you purchase, you get a third candy for free. The free candy must have a cost that is less than or equal to the minimum cost of the two candies purchased. Calculate the minimum cost of purchasing all candies.
Problem
Approach
Steps
Complexity
Input: The input consists of an array `cost`, where each element represents the cost of a candy.
Example: Input: cost = [3, 5, 7]
Constraints:
• 1 <= cost.length <= 100
• 1 <= cost[i] <= 100
Output: The output should be a single integer, representing the minimum cost of buying all the candies while making use of the 'buy 2, get 1 free' offer.
Example: Output: 10
Constraints:
• The result should be a non-negative integer.
Goal: Minimize the total cost by selecting pairs of candies to buy and making use of the third free candy when applicable.
Steps:
• Sort the candy prices in descending order.
• For every three consecutive candies, only pay for the first two.
• Sum up the costs of the candies you actually paid for to get the minimum cost.
Goal: The problem constraints ensure that the array size is manageable and that the candy costs are within a reasonable range.
Steps:
• The number of candies is at most 100.
• Each candy has a cost between 1 and 100.
Assumptions:
• The input is always valid and contains at least one candy.
Input: cost = [3, 5, 7]
Explanation: The optimal strategy is to buy the candies with costs 7 and 5, then take the candy priced at 3 for free. This results in a total cost of 5 + 7 = 10.

Input: cost = [4, 9, 3, 6, 2, 1]
Explanation: The optimal strategy is to buy candies with costs 9 and 6, then take the candy priced at 4 for free. After that, buy candies with costs 3 and 2, then take the candy priced at 1 for free. This results in a total cost of 9 + 6 + 3 + 2 = 17.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus