Minimum Cost of Buying Candies With Discount

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.

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.

Example 1
Inputcost = [1,2,3]
Output5
Buying candies with costs 2 and 3 allows the candy with cost 1 to be taken for free, for a total cost of 5.
Example 2
Inputcost = [6,5,7,9,2,2]
Output23
Buy candies with costs 9 and 7 to get 6 free, then buy candies with costs 5 and 2 to get the last 2 free, for a total cost of 23.

Constraints

  • 1 <= cost.length <= 100
  • 1 <= cost[i] <= 100

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate