The Minimum Cost of Buying Candies With Discount problem involves a shop where for every two candies you buy, you get one candy for free. The catch is that the free candy must have a cost less than or equal to the minimum of the two candies you just purchased. You are given an array of candy costs and need to find the minimum total cost to acquire all the candies in the shop.
This is a standard Minimum Cost of Buying Candies interview question for entry-level roles at companies like Garmin and Amazon. It tests a candidate's ability to apply a Greedy strategy to maximize savings. It evaluates if you can identify that you should always use the "free" slot for the most expensive candy possible that satisfies the condition.
The Greedy interview pattern with Sorting is perfect here.
Candy costs: [6, 5, 2, 2, 8, 2].
[8, 6, 5, 2, 2, 2].8 and 6, get 5 for free. (Cost: 14)2 and 2, get 2 for free. (Cost: 4)14 + 4 = 18.
If you had paired them differently, you might have gotten a cheaper candy (like 2) for free, which wouldn't be as efficient.[2, 2, 2, 5, 6, 8] and take every third, you get the smallest ones for free, which is the opposite of what you want.Whenever you have a "buy X get Y free" problem, Greedy with Sorting is almost always the answer. To minimize the cost, you want to get the most expensive possible items for free. Sorting descending allows you to sacrifice the top two costs to get the third-highest cost for free.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Buy Two Chocolates | Easy | Solve | |
| Maximum Units on a Truck | Easy | Solve | |
| Minimum Subsequence in Non-Increasing Order | Easy | Solve | |
| Apple Redistribution into Boxes | Easy | Solve | |
| How Many Apples Can You Put into the Basket | Easy | Solve |