마트에 회원으로 가입하면 10일간 하루에 1품목을 할인 행사가로 구입할 수 있습니다. 원하는 품목들의 모든 수량을 할인가에 사고 싶다고 할 때, 회원가입 가능한 날이 며칠 있는 지 구하는 문제입니다.
원하는 품목들의 array want
와 품목별 수량 number
가 주어집니다. number
를 품목별 목표까지 남은 수량
으로 사용하겠습니다. 편의를 위해 우선 dictionary에 품목별 index를 저장합니다.
날짜별 할인품목의 array인 discount
를 읽으며 해당 품목의 index를 찾아 number
에서 수량을 1 빼줍니다. 회원가입 혜택은 10일간만 유지되기 때문에, 초기 10일 이후부터는 앞쪽부터 다시 수량을 더해줍니다. 이런 작업을 반복하며 매번 가입 가능한지 check
method로 확인합니다.
문제에서 number 원소들의 합이 10
이라는 강한 조건을 줬기 때문에, number
의 원소가 음수가 되는 상황에 대해 신경쓰지 않고 편하게 해결할 수 있었습니다.
import java.util.*;
class Solution {
public int solution(String[] want, int[] number, String[] discount) {
HashMap<String, Integer> dict = new HashMap<>();
for (int i = 0; i < want.length; i++) {
dict.put(want[i], i);
}
for (int i = 0; i < 10; i++) {
if (dict.get(discount[i]) == null) {
continue;
}
number[dict.get(discount[i])]--;
}
int answer = check(number);
for (int i = 0; i < discount.length - 10; i++) {
if (dict.get(discount[i]) != null) {
number[dict.get(discount[i])]++;
}
if (dict.get(discount[i + 10]) != null) {
number[dict.get(discount[i + 10])]--;
}
answer += check(number);
}
return answer;
}
public int check(int[] number) {
for (int i = 0; i < number.length; i++) {
if (number[i] != 0) {
return 0;
}
}
return 1;
}
}