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
Minimum Cost of Buying Candies With Discount INPUT Original Array: cost[] 1 [0] 2 [1] 3 [2] 4 [3] 5 [4] 6 [5] Discount Rule: Buy 2 candies --> Get 1 FREE (cheapest of the 3) cost = [1,2,3,4,5,6] 6 candies total ALGORITHM STEPS 1 Sort Descending [6,5,4,3,2,1] 2 Group by 3 Take every 3rd FREE 3 Skip index % 3 == 2 Free: index 2, 5 4 Sum Paid Items 6+5+3+2 = 16 Sorted Groups: 6 5 4 FREE! 3 2 1 FREE! Green = PAY | Red = FREE FINAL RESULT Cost Breakdown: Candy 6: $6 (PAY) Candy 5: $5 (PAY) Candy 4: $0 (FREE) Candy 3: $3 (PAY) Candy 2: $2 (PAY) Candy 1: $0 (FREE) Total: 6+5+3+2 = 16 Output: 16 Original: 1+2+3+4+5+6 = 21 Saved: $5 (4+1 free) Key Insight: Sort candies in descending order, then take every 3rd candy free. This greedy approach ensures we always get the most expensive possible free candy in each group of 3. By buying the two most expensive first, the third (cheapest in group) qualifies as free, minimizing total cost. TutorialsPoint - Minimum Cost of Buying Candies With Discount | Greedy - Sort and Group Optimally
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