Post

[leetcode / easy] 2144. Minimum Cost of Buying Candies With Discount - implementation (Java)

[리트코드] 2144. Minimum Cost of Buying Candies With Discount 문제를 Java를 사용해 나머지를 활용한 조건문으로 풀었습니다.

[leetcode] 2144. Minimum Cost of Buying Candies With Discount

🙋‍♂️ 들어가며

문제를 읽어보니 조건이 N = 100이기에 정렬을 한 후, 나머지를 이용하면 되겠다

3으로 나눴을떄 나머지가 0, 1일때는 더하고 2일때는 넘어가는 것이다


✅ 정답 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Arrays;

class Solution {
    public int minimumCost(int[] cost) {
        // 1. 정렬 N logN
        Arrays.sort(cost);

        // 2. 뒤에서 2개 팔리면 3번째는 free
        int N = cost.length-1;
        int sum = 0;
        for (int i = N; i >= 0; i--) {
            if ( (N-i) % 3 == 0) sum += cost[i];
            else if ( (N-i) % 3 == 1 ) sum += cost[i];
        }

        // 3. 반환
        return sum;
    }
}
This post is licensed under CC BY 4.0 by the author.

Trending Tags