Leetcode Problem 2144. Minimum Cost of Buying Candies With Discount

2144. Minimum Cost of Buying Candies With Discount

Leetcode Solutions

Greedy Approach with Sorting

  1. Sort the array of candy costs in non-increasing order.
  2. Initialize a variable total_cost to 0 to keep track of the total cost.
  3. Iterate through the sorted array with an index i.
  4. For every index i that is not a multiple of 3 (since the third candy is free), add the cost of the candy at index i to total_cost.
  5. Return the value of total_cost as the minimum cost to buy all candies.
UML Thumbnail

Counting Sort with Greedy Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...