주식가격

magicdrill·2025년 4월 14일
0

주식가격

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

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer;
    
    /*
    answer.resize(prices.size(), 0);
    for (int i = 0; i < prices.size(); i++) {
		for (int j = i + 1; j < prices.size(); j++) {
			answer[i]++; 
			if (prices[i] > prices[j]) { 
                cout << answer[i] << " ";
				break;
			}
		}
	}
    */
    
    stack<int> st; 
    int length = prices.size();
    
    answer.resize(length, 0);
    for (int i = 0; i < length; ++i) {
        while (!st.empty() && prices[st.top()] > prices[i]){ 
            //st의 가장 위에 있는 인덱스(가장 나중에 들어온 숫자)에 해당하는 prices값이 현재 인덱스의 prices 값보다 크다면? -> 값이 증가한다면?
            answer[st.top()] = i - st.top(); 
            st.pop();
        }
        st.push(i);//st에 현재 인덱스 삽입
    }
    while (!st.empty()){
        answer[st.top()] = length - 1 - st.top();
        st.pop();
    }
    
    return answer;
}

0개의 댓글