[Programmers] 주식 가격

Date:

[Programmers] 주식 가격

Problem URL : 주식 가격

#include <string>
#include <vector>
#include <stack>
#include <iostream>
#define p pair<int,int>
#define MAX_LENGTH 100000
using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer;
    stack<p> s;

    int size = (int)prices.size();
    int period[MAX_LENGTH] = { 0, };

    s.push({ prices[0],0 });
    for (int i = 1; i < size; i++) {
        while (!s.empty() && s.top().first > prices[i]) {           
            int idx = s.top().second;
            s.pop();
            period[idx] = i - idx;
        }
        s.push({ prices[i],i });
    }

    while (!s.empty()) {
        int idx = s.top().second;
        s.pop();
        period[idx] = (size - 1) - idx;
    }

    for (int i = 0; i < size; i++) {
        cout << period[i] << " ";
        answer.push_back(period[i]);
    }
    return answer;
}

댓글