본문 바로가기

프로그래머스

프로그래머스(자바, Java) - Level2. 할인행사

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

 

프로그래머스

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

programmers.co.kr


주요 포인트 및 문제 리뷰

  • 문제자체가 크게 어렵지 않았지만 완료한 사람도 적은 것을 보아하니 올라온 지 얼마 안 된 문제 같다.
  • 회원자격은 항상 10일까지 유효하기 때문에 최대 행사 종료 10일 전까지 확인하면 된다.
  • 할인하는 제품은 하루 하나씩만 구매할 수 있다.
  • 원하는 제품을 모두 구매할 수 없을 수도 있다.

 


소스코드

  • 원하는 제품과 그 개수를 관리하는 wantMap을 refresh라는 method를 통하여 만들어준다.
  • canBuy라는 method를 돌면서 원하는 품목을 살 수 있는지 확인한다.
  • canBuy 실행 후 wantMap의 모든 Value들이 0일 경우 원하는 제품을 모두 구매한 경우이니 answer에 1을 더한다.
  • canBuy 실행 후 wantMap에 변동이 생겼기 때문에 다음 실행에 영향을 주기 때문에 다음 실행 전에 초기화한다.
import java.util.*;
class Solution {
    Map<String, Integer> wantMap;


    public int solution(String[] want, int[] number, String[] discount) {
        int answer = 0;

        this.wantMap = new HashMap<>();

        for (int i = 0; i <= discount.length - 10; i++) {
            refresh(want, number);
            if (canBuy(i, wantMap, discount)) {
                answer++;
            }
        }

        return answer;
    }

    public void refresh(String[] want, int[] number) {
        for (int k = 0; k < want.length; k++) {
            wantMap.put(want[k], number[k]);
        }
    }

    public boolean canBuy(int index, Map<String, Integer> wantList, String[] discountList) {

        for (int j = 0; j < 10; j++) {
            if (wantList.containsKey(discountList[index + j])) {
                if (wantList.get(discountList[index + j]) > 0) {
                    wantList.put(discountList[index + j], wantList.get(discountList[index + j]) - 1);
                }
            }
        }

        Set<String> ks = wantList.keySet();
        for (String key : ks) {
            if (wantList.get(key) > 0) {
                return false;
            }
        }
        return true;
    }
}

 

 

채점결과