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.
For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4.
Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return theminimum cost of buying all the candies.
Input: cost =[6,5,7,9,2,2]Output: 23Explanation: Buy candies with costs 9,7,6,5, and take candies with costs 2,2for free. Total cost =9+7+6+5=27, but you get two candies for free, so total cost =23.
Input: cost =[5,5]Output: 10Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.Hence, the minimum cost to buy all candies is5+5=10.
To minimize the total cost, always buy the most expensive candies first. For every two candies bought, take the cheapest available (among the remaining) for free. Sorting the array in descending order allows us to always pick the most expensive ones to pay for, and skip every third candy (the free one).
classSolution {
public:int minimumCost(vector<int>& cost) {
sort(cost.rbegin(), cost.rend());
int ans =0;
for (int i =0; i < cost.size(); ++i) {
if (i %3!=2) ans += cost[i];
}
return ans;
}
};
classSolution {
publicintminimumCost(int[] cost) {
Arrays.sort(cost);
int ans = 0, n = cost.length;
for (int i = n - 1, cnt = 0; i >= 0; i--, cnt++) {
if (cnt % 3 != 2) ans += cost[i];
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
funminimumCost(cost: IntArray): Int {
cost.sortDescending()
var ans = 0for (i in cost.indices) {
if (i % 3!=2) ans += cost[i]
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
defminimumCost(self, cost: list[int]) -> int:
cost.sort(reverse=True)
ans =0for i, v in enumerate(cost):
if i %3!=2:
ans += v
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnminimum_cost(cost: Vec<i32>) -> i32 {
letmut cost = cost;
cost.sort_by(|a, b| b.cmp(a));
letmut ans =0;
for (i, v) in cost.iter().enumerate() {
if i %3!=2 {
ans += v;
}
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
minimumCost(cost: number[]):number {
cost.sort((a, b) =>b-a);
letans=0;
for (leti=0; i<cost.length; ++i) {
if (i%3!==2) ans+=cost[i];
}
returnans;
}
}