본문 바로가기

알고리즘 공부 및 문제 풀이/프로그래머스(PRO)

[pro] 프로그래머스 level2 131127 할인 행사 (Java) - 시뮬레이션

[문제]

https://school.programmers.co.kr/learn/courses/30/lessons/131127

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

[풀이]

Map을 이용해서 disccount 목록을 이동시켜가며 비교한다. 

단순 시뮬레이션 문제!

 

[코드]

 

import java.util.*;

class Solution {
    public int solution(String[] want, int[] number, String[] discount) {
        int answer = 0;
        //회원등록시 정현이가 원하는 제품을 모두 할인 받을 수 있는 회원등록 날짜의 총 일수를 return
        
        Map<String, Integer> hm = new HashMap<>(); //종류:개수
        for(int i=0; i<10; i++){
            hm.put(discount[i], hm.getOrDefault(discount[i], 0)+1);
        }
        
        if(compareToWant(hm, want, number)) answer = 1;
        //want:number와 discount 비교
        for(int i=0; i<discount.length-10; i++){
            hm.replace(discount[i], hm.get(discount[i])-1);
            hm.put(discount[i+10], hm.getOrDefault(discount[i+10], 0)+1);
            
            if(compareToWant(hm, want, number)) answer++;
        }
        
        return answer;
        
    }
    
    public boolean compareToWant(Map<String, Integer> hm, String[] want, int[] number){
        for(int i=0; i<want.length; i++){
            if(!hm.containsKey(want[i]) || hm.get(want[i])!=number[i]){
                return false;
            }
        }
        return true;
    }
}