할인행사

개굴이·2023년 8월 24일
0

코딩테스트

목록 보기
3/58
post-thumbnail

프로그래머스 할인행사

String[] want 물품을
int[] number 개수만큼 //원소의 합은 10

String[] discount 에서 할인하는 날에 구매하려면
가입해야하는 날 총 일수 int result
가입한날부터 열흘간 구매 가능
원하는걸 모두 구매해야하고 안되면 return 0;

HashMap<물품, 개수>

i = 0 -> want.length 만큼 돌면서
HashMap에 물품 이름과 개수를 넣는다.

i = 0 -> discount.length - 9만큼 돌면서
HashMap에 ((구매 가능한))물품 이름과 개수를 넣는다.

두 개의 HashMap을 비교하여
for String key : HashMap.ketSet()
HashMap.get(key) == 두번째 HashMap.get(key)
일치하면 패스 아니면 break 해서
조건에 만족하면 result++:

import java.util.*;

class Solution {
    public int solution(String[] want, int[] number, String[] discount) {
        int result = 0;
        
        HashMap<String, Integer> need = new HashMap<>();
        
        for(int i = 0; i < want.length; i++) {
            need.put(want[i], number[i]);
        }
        
        for(int i = 0; i < discount.length - 9; i++) {
            HashMap<String, Integer> possible = new HashMap<>();
            for(int j = 0; j < 10; j++) {
                if(possible.containsKey(discount[i + j]))
                    possible.put(discount[i + j], possible.get(discount[i + j]) + 1);
                else
                    possible.put(discount[i + j], 1);
            }
           
            result++;
            
            for(String key : need.keySet()) {
                if(need.get(key) == possible.get(key)){}
                else {
                    result--;
                    break;
                }
            }
        }

        return result;
    }
}

0개의 댓글