728x90
문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한사항
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
Solution
#include <string>
#include <vector>
#include <map>
using namespace std;
vector<int> solution(vector<int> prices) {
vector<pair<int,int>> stack;
map<int,int> answer;
int seconds;
vector<int> answer2;
//첫번째 함수 넣기
stack.push_back(make_pair(0,prices[0]));
for (int i=1; i<prices.size(); i++){
//새로 들어온 주식 가격이 떨어지는 경우 stack에서 주식 가격을 꺼내서 떨어지는 시간을 계산하여 저장
//그렇지 않은 경우에는 push
while (true){
if (stack.back().second > prices[i]){
seconds = stack.back().first;
stack.pop_back();
answer[seconds] = i-seconds;
}
else {
stack.push_back(make_pair(i, prices[i]));
break;
}
}
}
//stack에 남은 주식들은 끝날때까지 떨어지지 않는다고 계산
while (stack.size() != 0){
seconds = stack.back().first;
stack.pop_back();
answer[seconds] = prices.size()-seconds-1;
}
//결과값 넣기
for (int i=0; i<prices.size(); i++){
answer2.push_back(answer[i]);
}
return answer2;
}
728x90
'알고리즘' 카테고리의 다른 글
[프로그래머스] H-index c++ (0) | 2021.08.23 |
---|---|
[프로그래머스] 가장 큰 수 c++ (0) | 2021.08.23 |
[프로그래머스] 다리를 지나는 트럭 c++ (0) | 2021.08.15 |
[프로그래머스] 프린터 c++ (0) | 2021.08.15 |
[프로그래머스] 위클리챌린지 2주차 상호 평가 C++ (0) | 2021.08.15 |