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

[프로그래머스/Java] 할인 행사

by 현장 2026. 1. 2.

-Code

import java.util.*;

class Solution {
    public int solution(String[] want, int[] number, String[] discount) {
        int answer = 0;
        // want의 갯수랑 비교 갯수가 모두 같아야 하므로 map을 통해 검사하기 위해 셋팅
        Map<String, Integer> wantCnt = new HashMap<>();
        for (int i = 0; i < want.length; i++) {
            wantCnt.put(want[i], number[i]);
        }
        // 첫날 가입시 10일간 count 저장
        Map<String, Integer> discountCnt = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            String name = discount[i];
            discountCnt.put(name, discountCnt.getOrDefault(name, 0) + 1);
        }
        // (length - 10) 횟수만큼 돌면서 검사
        for (int i = 10; i <= discount.length; i++) {
            boolean flag = true;
            // 키셋을 기준으로 갯수가 같지 않으면 false 반환
            for (String name : wantCnt.keySet()) {
                if (wantCnt.get(name) != discountCnt.get(name)) {
                    flag = false;
                }
            }
            // 갯수가 같으면 answer++
            if (flag) {
                answer++;
            }
            // 마지막이 아닌 경우 값 변경
            if (i < discount.length) {
                String prev = discount[i - 10];
                discountCnt.put(prev, discountCnt.get(prev) - 1);
                String next = discount[i];
                discountCnt.put(next, discountCnt.getOrDefault(next, 0) + 1);
            }
        }
        return answer;
    }
}

처음에 인덱스 문제와 마지막 가입일을 검사하지 않아서 틀렸었습니다. 그래서 길이보다 작은 경우에만 개수 변경하고 인덱스 범위를 길이 이하로 잡아서 해결했습니다.