본문 바로가기
Beakjoon&프로그래머스/Java

[프로그래머스/Java] 체육복

by 현장 2026. 3. 10.

-Code

import java.util.*;

class Solution {
    public int solution(int n, int[] lost, int[] reserve) {
        // 각 번호의 사람이 몇개의 체육복을 가졌는지 확인
        int[] clothesCnt = new int[n + 1];
        Arrays.fill(clothesCnt, 1);
        for (int num : lost) clothesCnt[num]--;
        for (int num : reserve) clothesCnt[num]++;
        // 빌려줄 수 있는지 확인
        for (int i = 1; i <= n; i++) {
            if (clothesCnt[i] == 2) {
                if(clothesCnt[i - 1] == 0) {
                    clothesCnt[i - 1]++;
                    clothesCnt[i]--;
                } else if (i + 1 <= n && clothesCnt[i + 1] == 0) {
                    clothesCnt[i + 1]++;
                    clothesCnt[i]--;
                }
            }
        }
        // 체육복을 입은 사람수
        int answer = 0;
        for (int i = 1; i <= n; i++) {
            answer += clothesCnt[i] >= 1 ? 1 : 0;
        }
        return answer;
    }
}

처음에는 boolean으로 계산하려 했으나 그 경우 도난 당했을 경우 처리에 문제가 생겨서 힌트로 체육복 보유 갯수로 하라는 것을 보고 수정해 해결했고 범위문제가 있어서 해당 부분을 바꿔서 해결했습니다.