프로그래머스 Lv. 2 할인 행사 JAVA

YB·2024년 12월 30일

링크텍스트

설명

이 문제는 HashMap을 이용해 풀었다. HashMap의 키는 구매하고자 하는 제품을 값은 해당 제품의 구매하고자 하는 수량을 저장했다. 이후 for문을 사용해 할인된 제품을 하나씩 확인하며 해당 제품이 내가 원하는 제품이라면 그 수량을 1씩 차감했다.

코드

import java.util.*;
import java.io.*;

class Solution {
    public int solution(String[] want, int[] number, String[] discount) {
        int answer = 0;
        
        HashMap<String,Integer> hm = new HashMap<>();
        for(int i=0;i<want.length;i++){
            hm.put(want[i],number[i]);
        }
        
        for(int i=0;i<discount.length;i++){
            HashMap<String, Integer> tm = new HashMap<>(hm);
            if(i+10>discount.length) break;
            for(int j=i;j<i+10;j++){
                if(tm.containsKey(discount[j])){
                    tm.put(discount[j],tm.get(discount[j])-1);                    
                }
            }
            boolean register = true;
            for(String key: tm.keySet()){
                if(tm.get(key)>0){
                    register =false;
                    break;
                }
            }
            if(register) answer++;
        }
        
        return answer;
    }
}

다른 사람의 풀이

링크텍스트

profile
안녕하세요

0개의 댓글