본문 바로가기

코딩테스트/programmers

롤케이크 자르기

https://school.programmers.co.kr/learn/courses/30/lessons/132265

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

철수와 동생이 먹게되는 토핑의 종류 수가 같아야 한다.

 

토핑별로 몇개가 있는지 카운트해주고(countBy)

 

왼쪽부터 커팅했을 때 철수가 갖게 되는 토핑의 종류(culsoo.size())와, 남아있는 토핑의 종류(countBy.size())를 카운트해가며 비교했다.

 

import java.util.*;

class Solution {
    public int solution(int[] topping) {
        
        Map<Integer, Integer> countBy = new HashMap();
        for (int t : topping) {
            int cnt = countBy.getOrDefault(t, 0);
            countBy.put(t, ++cnt);
        }
        
        int answer = 0;
        
        Set<Integer> chulsoo = new HashSet();
        for (int t : topping) {
            int cnt = countBy.get(t);
            if (cnt > 1) {
                countBy.put(t, --cnt);
            } else {
                countBy.remove(t);
            }
            chulsoo.add(t);
            
            if (chulsoo.size() == countBy.size()) answer++;
            else if (chulsoo.size() > countBy.size()) break;
            
        }
        
        return answer;
    }
}

'코딩테스트 > programmers' 카테고리의 다른 글

숫자 변환하기  (0) 2023.11.03
프렌즈4블록  (0) 2023.11.03
파일명 정렬  (0) 2023.10.31
스킬트리  (0) 2023.10.28
주식가격  (0) 2023.10.25