고흐의 연구실/자료구조와 알고리즘

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

전고흐 2020. 10. 23. 03:15
728x90

문제설명

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

제한사항

prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.

prices의 길이는 2 이상 100,000 이하입니다.

입출력 예

코드

#include <string>
#include <vector>

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer;

    for(int i=0; i<prices.size(); i++){
        int count = 0;
        for(int j=i+1; j<prices.size(); j++){
            count++;
            if(prices[i]>prices[j]){
                break;
            }
        }
        answer.push_back(count);
    }
    return answer;
}

 

아쉬운 점

 - 스택/큐 문제인데 안씀..

 - C++에 #include <stack>이라는게 있다...?

 

+ 스택을 사용한 코드 참조하기

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

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size());
    stack<int> s;
    int size = prices.size();
    for(int i=0;i<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()] = size-s.top()-1;
        s.pop();
    }
    return answer;
}
728x90