1.문제
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 the minimum cost of buying all the candies
가게에서 사탕을 할인해서 팔고 있다. 사탕이 두 개 팔릴 때마다, 그 가게는 세 번째 사탕을 무료로 준다.
고객은 선택한 사탕의 가격이 구매한 두 개의 사탕의 최소 가격보다 낮거나 같으면 무료로 가져갈 사탕을 선택할 수 있다.
이러한 조건에서 모든 사탕을 사는 최소한의 비용을 리턴하는 문제이다.
Example 1
Input: cost = [1,2,3]
Output: 5
Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.
Example 2
Input: cost = [6,5,7,9,2,2]
Output: 23
Explanation: The way in which we can get the minimum cost is described below:
- Buy candies with costs 9 and 7
- Take the candy with cost 6 for free
- We buy candies with costs 5 and 2
- Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.
Example 3
Input: cost = [5,5]
Output: 10
Explanation: 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 is 5 + 5 = 10.
Constraints:
- 1 <= cost.length <= 100
- 1 <= cost[i] <= 100
2.풀이
- 배열을 내림차순으로 정렬한다.
- 만약 배열의 길이가 3 미만이라면 배열안 모든 숫자의 합을 리턴
- 배열의 길이가 3이상이라면 앞에서부터 2개의 숫자는 sum에 더하고 나머지 하나는 배열에서 삭제한다.
- for문을 돌면서 만약 남은 배열의 길이가 3미만이 된다면 나머지 숫자들을 모두 sum에 더해주고 리턴한다.
/**
* @param {number[]} cost
* @return {number}
*/
const minimumCost = function (cost) {
let sum = 0;
cost.sort((a, b) => b - a); // 내림차순 정렬
if (cost.length <= 2) {
// 배열의 길이가 2 이하면 그대로 요소들의 합을 리턴
sum = cost.reduce((sum, current) => sum + current);
return sum;
} else {
for (let i = 0; i < cost.length; i += 3) {
// 앞의 두개 숫자를 배열에서 빼서 sum에 더하고 그 다음 숫자를 배열에서 삭제한다
if (cost.length >= 3) {
sum += cost.shift();
sum += cost.shift();
cost.shift();
i -= 3;
} else {
// 남은 배열의 길이가 3 미만이면 남은 숫자를 다 더해준다.
sum += cost.reduce((sum, current) => sum + current);
}
}
return sum;
}
};
3.결과
