[프로그래머스] 주식 가격 C++
in Study on Coding Test
큐를 이용하여 푸는 문제
정답제출코드
#include <string>
#include <vector>
#include <queue>
using namespace std;
vector<int> solution(vector<int> prices) {
vector<int> answer;
queue<int> q;
// 큐 생성
int len = prices.size();
for (int i = 0; i < len; ++i)
q.push(prices[i]);
int start_index = 1;
while(!q.empty())
{
// 큐에서 숫자 하나를 뽑음.
int count = q.front();
q.pop();
// 초를 세기 시작하자.
int second = 0;
for (int i = start_index; i < len; ++i)
{
// 뽑은 숫자보다 낮아진 숫자가 등장할 경우
// 초를 증가시킨 뒤 중단한다.
if (count > prices[i])
{
second++;
break;
}
second++;
}
// 누적한 초를 증가시키고 시작 인덱스를 1 증가시킨다.
answer.push_back(second);
start_index++;
}
return answer;
}
주제가 스택/큐 문제라서 헷갈렸는데, 큐를 쓸지 스택을 쓸지 고민을 많이 했던 것 같다.
힌트를 보니 큐를 사용한 풀이가 많아서 고민한 끝에 큐를 사용해서 풀었다.