Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: 롤케이크 자르기 본문

Java

프로그래머스: 롤케이크 자르기

Daeryuk Kim 2024. 3. 20. 22:52
import java.util.HashMap;

class Solution {
    public int solution(int[] topping) {
        int answer = 0;
        HashMap<Integer, Integer> toppingCnt = new HashMap<>();
        int uniqueToppings = 0; // 고유 토핑 종류의 수

        // 전체 토핑 종류의 수를 계산합니다.
        for (int top : topping) {
            if (!toppingCnt.containsKey(top)) {
                uniqueToppings++;
            }
            toppingCnt.put(top, toppingCnt.getOrDefault(top, 0) + 1);
        }

        HashMap<Integer, Integer> leftToppings = new HashMap<>();
        int leftUniqueToppings = 0; // 왼쪽 조각의 고유 토핑 종류의 수

        for (int i = 0; i < topping.length - 1; i++) {
            int current = topping[i];
            // 왼쪽 조각에 토핑을 추가합니다.
            if (!leftToppings.containsKey(current)) {
                leftUniqueToppings++;
            }
            leftToppings.put(current, leftToppings.getOrDefault(current, 0) + 1);

            // 전체 토핑 종류에서 현재 토핑의 수를 감소시킵니다.
            if (toppingCnt.get(current) == 1) {
                uniqueToppings--;
            } else {
                toppingCnt.put(current, toppingCnt.get(current) - 1);
            }

            // 왼쪽과 오른쪽의 고유 토핑 종류 수가 같으면 정답을 1 증가시킵니다.
            if (leftUniqueToppings == uniqueToppings) {
                answer++;
            }
        }

        return answer;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] topping = {1, 2, 1, 3, 1, 4, 1, 2};
        
        int result = sol.solution(topping);
        System.out.println(result); // 결과 출력
    }
}

'Java' 카테고리의 다른 글

프로그래머스: [3차]파일명 정렬  (0) 2024.03.21
프로그래머스: 오픈채팅방  (0) 2024.03.20
프로그래머스: 스킬트리  (0) 2024.03.20
프로그래머스: 땅따먹기  (0) 2024.03.20
프로그래머스: 주식가격  (0) 2024.03.19