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 its cost 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 ith candy, return the minimum cost of buying all the candies.

30:00

Minimum Cost of Buying Candies With Discount
easy
Free written solution
Topics
Companies

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 its cost 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 ith candy, return the minimum cost of buying all the candies.

Example 1:
Input: {"cost":[1,2,3]}
Output: 5
Constraints:
  • 1≤cost.length≤1001 \leq \text{cost.length} \leq 100

  • 1≤cost[i]≤1001 \leq \text{cost}[i] \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"cost":[1,2,3]}

3 candies on the counter. Each free candy must cost no more than the cheaper of the two you pay for.

the counter, as given

1

2

3

paid

0

saved

0

Variables
VariableValue
i-1
total0
DepthFunction Call
Stack empty
0/6