Problem 982
Minimum Cost of Buying Candies With Discount
Easy · 10 pts · Array, Greedy, Sorting
Problem
A shop has a deal: for every two candies you buy, you get a third candy for free, as long as its price is at most the cheaper of the two bought. Find the minimum cost to get all the candies. Sort the prices from highest to lowest and go in groups of three: pay for the first two of each group and take the third for free. That way every free candy is as expensive as possible.
Input
The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].
Output
Print the minimum total cost.
Constraints
1 <= N <= 100; 1 <= price <= 100
Example input
6 6 5 7 9 2 2
Example output
23
Explanation
For prices 6 5 7 9 2 2, sorted from highest they are 9 7 6 5 2 2. Pay 9 and 7 and get 6 free, pay 5 and 2 and get 2 free. The total cost is 23.