본문 바로가기

problem solving

[프로그래머스]주식가격

답의 벡터인 answer의 크기를 prices.size()로 할당해서 값의 분배를 편하게 할 수 있도록 한다.

큐를 사용해서  한 번의 순회로 끝낼 수 있도록 했다.

마지막으로 순회가 끝날 때까지 하락하지 않은 값들은 큐에 여전히 남아있으므로

이를 while문으로 따로 처리했다.

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
31
32
33
34
35
36
37
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
 
using namespace std;
 
vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size());
    
    queue<pair<intint>> mQ;
    for(int j = 0; j < prices.size(); j++) {
        int lim = mQ.size();
        for(int i = 0; i < lim; i++) {
            int pos = mQ.front().first;
            int count = mQ.front().second;
            mQ.pop();
            
            if (prices[j] < prices[pos]) { 
                answer[pos] = count + 1;
            }
            else {
                mQ.push( { pos, count + 1 } );
            }
        }
        mQ.push( { j, 0 } );
    }
    while (!mQ.empty()) {
        int pos = mQ.front().first;
        int count = mQ.front().second;
        mQ.pop();
        
        if(answer[pos]) { continue; }
        answer[pos] = count;
    }
    return answer;
}
cs

'problem solving' 카테고리의 다른 글

[프로그래머스]문자열 압축  (0) 2020.03.07
[프로그래머스]프린터  (0) 2020.03.07
[프로그래머스]쇠막대기  (0) 2020.03.07
[프로그래머스]기능개발  (0) 2020.03.07
[프로그래머스]스킬트리  (0) 2020.03.07