#2144

Minimum Cost of Buying Candies With Discount

Easy
ArrayGreedySortingGreedy AlgorithmsSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting the candy costs in descending order, we can maximize the value of the free candy we get. We buy the most expensive candies first and always take the next cheapest candy that is eligible for free.

⚙️

Algorithm

5 steps
  1. 1Step 1: Sort the candies in descending order of cost.
  2. 2Step 2: Initialize a total cost variable to 0.
  3. 3Step 3: Iterate through the sorted list, buying two candies at a time.
  4. 4Step 4: For every two candies bought, skip the next candy (which is the free one).
  5. 5Step 5: Add the costs of the bought candies to the total cost.
solution.py7 lines
1def minimumCost(cost):
2    cost.sort(reverse=True)
3    total_cost = 0
4    for i in range(len(cost)):
5        if (i % 3) != 2:
6            total_cost += cost[i]
7    return total_cost

Complexity note: The time complexity is O(n log n) due to the sorting step, which is the most time-consuming operation. The subsequent iteration through the list is O(n), making the overall complexity dominated by the sorting step.

  • 1Buying the most expensive candies first maximizes the value of the free candy.
  • 2Sorting the costs allows for a structured approach to minimize total spending.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.