GitHubSeob
C++ / 프로그래머스 / 할인 행사 본문
문제 |
https://school.programmers.co.kr/learn/courses/30/lessons/131127
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제풀이 |
간단하게 풀 방법이 떠오르지 않아 항상 반복문을 통해 같은지를 판별하도록 했다.
10일 연속으로 제품을 구매하므로 idx가 0~9일때는 삭제하는 물품없이 다 map을 이용하여 저장하였다.
대신에 want에 있는 제품과 같을때만 저장하였다.
want에 있는 물품이면 map의 해당 제품에 수량을 1씩 더해준다.
그 다음 want에 있는 제품과 개수, 구매한 목록에 있는 제품과 개수가 모두 일치하거나 구매한 목록의 수량이 더 많다면 answer에 1을 더하였다.
idx가 10부터는 left, right를 두어 left에 있는 제품은 map에서 -1을 하거나 삭제, right에 있는 제품은 map에 추가하였다.
위와 마찬가지로 날이 바뀔때마다 반복문을 통해 같은지를 판별하고 answer에 1을 더한다.
코드 |
#include <string>
#include <vector>
#include <map>
using namespace std;
int solution(vector<string> want, vector<int> number, vector<string> discount) {
int answer(0), idx(0), left(0), right(0);
bool flag(true);
map<string, int>want_list;
map<string, int>purchase_list;
for (idx = 0; idx < want.size(); ++idx) {
want_list[want[idx]] = number[idx];
}
for (idx = 0; idx < 10 && idx < discount.size(); ++idx) {
if (want_list.find(discount[idx]) != want_list.end()) {
++purchase_list[discount[idx]];
}
flag = true;
for (auto iter = want_list.begin(); iter != want_list.end(); ++iter) {
if (iter->second > purchase_list[iter->first]) {
flag = false;
break;
}
}
if (flag) {
++answer;
}
}
left = -1;
right = 9;
while (right + 1 < discount.size()) {
++left;
++right;
if (want_list.find(discount[right]) != want_list.end()) {
++purchase_list[discount[right]];
}
if (purchase_list[discount[left]] == 1) {
purchase_list.erase(discount[left]);
}
else if (purchase_list[discount[left]] > 1) {
--purchase_list[discount[left]];
}
flag = true;
for (auto iter = want_list.begin(); iter != want_list.end(); ++iter) {
if (iter->second > purchase_list[iter->first]) {
flag = false;
break;
}
}
if (flag) {
++answer;
}
}
return answer;
}
'Programmers > Level 2' 카테고리의 다른 글
C++ / 프로그래머스 / k진수에서 소수 개수 구하기 (0) | 2023.08.10 |
---|---|
C++ / 프로그래머스 / 프로세스 (0) | 2023.07.26 |
C++ / 프로그래머스 / 튜플 (0) | 2023.07.16 |
C++ / 프로그래머스 / 의상 (0) | 2023.07.16 |
C++ / 프로그래머스 / [1차] 캐시 (0) | 2023.07.11 |