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, 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 i-th candy, return the minimum cost of buying all the candies.

Input & Output

Example 1 — Basic Case
$ Input: cost = [1,2,3,4,5,6]
Output: 16
💡 Note: Sort to [6,5,4,3,2,1]. Group 1: pay 6+5=11, get 4 free. Group 2: pay 3+2=5, get 1 free. Total = 11+5 = 16.
Example 2 — Minimum Size
$ Input: cost = [6,5,7,9,2,2]
Output: 23
💡 Note: Sort to [9,7,6,5,2,2]. Group 1: pay 9+7=16, get 6 free. Group 2: pay 5+2=7, get 2 free. Total = 16+7 = 23.
Example 3 — Edge Case
$ Input: cost = [5,5]
Output: 10
💡 Note: Only 2 candies, no free candy available. Must buy both: 5+5 = 10.

Constraints

  • 1 ≤ cost.length ≤ 100
  • 1 ≤ cost[i] ≤ 100

Visualization

Tap to expand
Buy-2-Get-1-Free Candy Discount ProblemInput: [1,2,3,4,5,6]123456Sort Descending: [6,5,4,3,2,1]654321Group 1: Pay 6+5, Free 4Group 2: Pay 3+2, Free 1Total Cost: (6+5) + (3+2) = 16🟢 Pay | 🟠 Free
Understanding the Visualization
1
Input
Array of candy costs [1,2,3,4,5,6]
2
Process
Sort descending and group by 3, pay for 2 most expensive per group
3
Output
Minimum total cost to buy all candies
Key Takeaway
🎯 Key Insight: Sort candies by price descending, then greedily group consecutive triplets to maximize savings
Asked in
Amazon 15 Microsoft 8
23.4K Views
Medium Frequency
~12 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen