Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[프로그래머스] 주식 가격 (C++) 본문

Problem Solving

[프로그래머스] 주식 가격 (C++)

흑개 2021. 11. 19. 23:37

https://programmers.co.kr/learn/courses/30/lessons/42584

 

코딩테스트 연습 - 주식가격

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요. 제한사항 prices의 각 가격은 1 이상 10,00

programmers.co.kr

#include <string>
#include <vector>
#include <stack>

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size());
    stack<int> s;
    for (int i=0; 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;
}

 

O(N^2) 로만 푸는 방법밖에 생각이 안나서 구글링..

 

stack을 이용하면 된다.

스택을 차례대로 쭉 쌓아주면서, stack의 top 인덱스 prices 값과, 현재 넣으려는 prices 값을 비교해서 현재 넣으려는 값이 top보다 작으면, 줄어든 것이므로 answer 을 갱신해준다. 이 과정을 stack 이 비지 않고, prices[s.top()]>prices[i] 일때까지 반복한다. 

 

가격이 떨어지지 않는 경우는 스택에 그대로 쭉 남아있을 것이므로, s.top() 을 이용해 값을 구해주고 pop을 해준다.

스택이 빌 때까지 반복한다.