프로그래머스/2레벨
주식가격/C++
Koalitsiya
2023. 1. 16. 15:10
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
스택에 주식 가격의 인덱스를 담고 해당 인덱스의 prices값과 prices[i]를 비교해서 prices[s.top()]이 더 크다면 answer에 i에서 s.top()을 뺀 값을 담는다. 비교가 끝난 후 스택이 비어있지 않다면 스택에 남아있는 값을 인덱스로 가지는 price는 가격이 떨어지지 않았으므로 prices.size() - s.top() - 1를 answer에 담는다.
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> prices) {
vector<int> answer(prices.size());
stack<int> s;
s.push(0);
for(int i = 1; i < prices.size(); i++) {
while(!s.empty() && prices[s.top()] > prices[i]) {
answer[s.top()] = i - s.top();
s.pop();
}
s.push(i);
}
while(!s.empty()) {
answer[s.top()] = prices.size() - s.top() - 1;
s.pop();
}
return answer;
}