코린이의 소소한 공부노트

[LeetCode/Easy] 2144. Minimum Cost of Buying Candies With Discount 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 2144. Minimum Cost of Buying Candies With Discount

무지맘 2023. 6. 21. 12:38

1. Input

1) int[] cost

- cost[i] = i번째 사탕의 가격

 

2. Output

1) 모든 캔디를 사는 데 필요한 최소 비용을 반환

- 캔디를 a, b 2개 사면 3번째 사는 캔디는 무료이다.

- 이때 무료로 살 수 있는 캔디의 가격은 ab의 가격 이하여야 한다.

 

3. Constraint

1) 1 <= cost.length <= 100

2) 1 <= cost[i] <= 100

 

4. Example

Input: cost = [6,5,7,9,2,2] -> Output: 23

설명:

- 7짜리와 9짜리 사탕을 사고, 6짜리를 무료로 받는다.

- 5짜리와 2짜리 사탕을 사고, 2짜리를 무료로 받는다.

- 필요한 비용은 7 + 9 + 5 + 2 = 23이다.

 

5. Code

1) 첫 코드(2023/06/21)

class Solution {
    public int minimumCost(int[] cost) {
        Arrays.sort(cost);
        int answer = 0;
        for(int i=cost.length-1; i>=0 ; i--){
            if((cost.length-i)%3!=0)
                answer += cost[i];
        }
        return answer;
    }
}

- 97%, 75%