코딩테스트/프로그래머스
[프로그래머스] 할인 행사 (Java)
개발자마이
2023. 2. 4. 01:53
반응형
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
접근 방식
해시맵 두 개를 활용하여 간단하게 해결할 수 있는 문제였다.
로직 설명
- 해시맵 map을 선언하여 want와 number 배열로부터 목표로 하는 할인 정보(제품명, 수량) 저장
- (discount 배열을 탐색하며) 해시맵 dMap을 선언하여 일별로 10일 간의 할인 정보 저장
- 생성된 dMap과 map을 비교하여 수량이 다른 경우 isIdentical 변수 false로 지정
- 두 해시맵이 동일하면 answer 증가
작성 코드
import java.util.*;
class Solution {
public int solution(String[] want, int[] number, String[] discount) {
int answer = 0;
int days = 10;
Map<String, Integer> map = new HashMap<>();
for(int i = 0; i < want.length; i++){
map.put(want[i], number[i]);
}
for(int i = 0; i < discount.length - days + 1; i++){
Map<String, Integer> dMap = new HashMap<>();
for(int j = 0; j < days; j++){
dMap.put(discount[i + j], dMap.getOrDefault(discount[i + j], 0) + 1);
}
Boolean isIdentical = true;
for(String key : map.keySet()){
if(map.get(key) != dMap.get(key)){
isIdentical = false;
break;
}
}
answer += isIdentical ? 1 : 0;
}
return answer;
}
}
Note
- 처음에 10일로 고정된 줄 모르고 number를 합산하여 days를 산출하고 있었다. 문제를 잘 읽자.
반응형