Minimum Cost of Buying Candies With Discount (LeetCode 2144): Solution and Explanation

Easy
Array
Greedy
Sorting

For every two candies you buy, you may take a third for free if it costs no more than the cheaper of the two. Return the least you must pay to get every candy.

Intuition

Every candy is either paid for or free, so paying the least means making the free candies worth as much as possible.

A free candy is capped by the cheaper of its two paid partners. A free candy needs two paid candies priced at or above it, so neither the most expensive nor the second most expensive candy can be free. The best you can hope for is the third most expensive going free.

Sorting from high to low and cutting into groups of three gives exactly that: in each group the third candy is the cheapest, so it qualifies, and the groups take the largest possible free values in order.

A last group of one or two candies has no free candy and is simply paid for.

Approach: Sort descending, every third candy is free

  1. Sort cost from most to least expensive.
  2. Walk the sorted list with index i.
  3. Add cost[i] to the total unless i % 3 == 2, which marks the free third candy of a group.
  4. Return the total.

Step-by-step example

cost = [1,2,3]
  1. Sort high to low: [3,2,1].
  2. i = 0: pay 3, total = 3.
  3. i = 1: pay 2, total = 5.
  4. i = 2: the 1 is no more than the cheaper paid candy (2), so it is free.
  5. Total paid = 5.

Code: Python, Java, C++

1class Solution:
2    def minimumCost(self, cost: List[int]) -> int:
3        cost.sort(reverse=True)
4        total = 0
5        for i in range(len(cost)):
6            if i % 3 != 2:
7                total += cost[i]
8        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates; the pass over the sorted prices is O(n). Counting sort on prices up to 100 would make it O(n + 100).

Space

O(1)

Only a running total is kept, apart from the sort's own memory.

Other approaches

Counting sort on prices (time O(n + 100), space O(100))

Prices are at most 100, so count how many candies have each price and walk prices from 100 down to 1, tracking the position modulo 3.

Total minus free candies (time O(n log n), space O(1))

Sum all prices, then subtract the prices at sorted positions 2, 5, 8 and so on. Same idea, framed as savings.

Common mistakes

  • Sorting in ascending order and taking every third from the start. That frees the cheapest candies instead of the most expensive ones you are allowed.
  • Taking the most expensive candy free. It is never allowed, because no cheaper partner pair covers it.
  • Assuming a group of two still earns a free candy. The discount needs two paid candies plus a third.
  • Forgetting that equal prices are fine: the free candy may cost exactly as much as the cheaper paid one.

Frequently asked questions

Why is sorting high to low optimal?

The k-th free candy needs at least 2k paid candies priced at or above it, so it can be at best the (3k)-th most expensive candy. The sorted grouping reaches that bound for every k at once.

Does the order I buy the candies in matter?

No. Only which candies go together in a group of three matters, and the sorted grouping picks those groups.

What if there are fewer than three candies?

Then no candy can be free and the answer is the plain sum of the prices.