코테 준비 2일차

아빠는 외계연·2022년 12월 20일
0

CodingTest

목록 보기
2/18

👑문제: [프로그래머스 Level2]

할인행사

문제 시 고려해야 할 점

자바에서는 map함수의 값을 변경할 때 get으로 꺼내온 뒤 put으로 다시 넣어주는 작업이 필요하다.
슬라이딩 윈도우 기법을 활용하여 문제를 해결하였다.

풀이 과정

import java.util.*;
class Solution {

    public boolean check(Map<String,Integer> map) {
        int flag = 0;
        Iterator<String> keys = map.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            if(map.get(key) > 0) {
                flag = 1;
                break;
            }
        }
        if(flag == 0) return true;
        return false;
    }
    public int solution(String[] want, int[] number, String[] discount) {
        int start = 0;
        int end = start + 10;
        int answer = 0;

        Map<String,Integer> map = new HashMap<>();

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

        //처음
        for(int i =0; i < 10; i++) {
            if(map.containsKey(discount[i]))  map.put(discount[i] , map.get(discount[i])-1);
        }
        if(check(map)) answer++;

        while(end < discount.length) {
            if(map.containsKey(discount[start])) map.put(discount[start] ,map.get(discount[start])+1);
            if(map.containsKey(discount[end])) map.put(discount[end] ,map.get(discount[end])-1);
            start++;
            end ++;
            if(check(map)) answer++;
        }
        return answer;
    }

}

느낀점

단순한 문제!

profile
Backend Developer

0개의 댓글