Geisha 2024. 5. 29. 14:57

이문제.. 이해하는게 힘들었다. 
결론은 한번의 회원가입으로 내가원하는 제품들을 모두 할인해서 10일안에 살수있는 날짜 수를 찾아야 했다.
처음부터 모두 2중반복문으로 하려고 하였으나 최대한 깔끔하게 이해되기 쉽게끔 작성하려고 노력했다.

Map.getOrDefault() 사용할 수 있는 좋은 기회였다. 덕분에 코드가 조금더 깔끔해 질 수 있었던 것 같다.

import java.util.*;

public class p할인행사 {
    public static HashMap<String,Integer> wantMap = new HashMap<>();
    public static HashMap<String,Integer> nowMap = new HashMap<>();

    public int solution(String[] want, int[] number, String[] discount) {

        int answer = 0;
        boolean available = true;

        for(int i = 0 ; i < want.length ; i++)
            wantMap.put(want[i],number[i]);

        for(int i = 0 ; i < 10 ; i++)
            nowMap.put(discount[i], nowMap.getOrDefault(discount[i],0)+1);

        available = check(want);

        if(available)
            answer++;

        for(int i = 10 ; i < discount.length ; i++){

            nowMap.put(discount[i],nowMap.getOrDefault(discount[i],0)+1);

            nowMap.put(discount[i-10],nowMap.getOrDefault(discount[i-10],0)-1);

            if(wantMap.getOrDefault(discount[i-10],0) > nowMap.get(discount[i-10])
                    || wantMap.getOrDefault(discount[i],0) > nowMap.get(discount[i]))
            {
                available = false;
                continue;
            }
            else
                available = check(want);
            if(available)
                answer++;
        }
        return answer;
    }
    public static boolean check(String[] want){
        for(int i = 0 ; i < want.length; i++){
            if(wantMap.get(want[i])>nowMap.getOrDefault(want[i],0)){
                return false;
            }
        }
        return true;
    }

}