본문 바로가기

Algorithm/프로그래머스

프로그래머스 주식가격 C++

반응형

프로그래머스 : 주식가격

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 


- 문제

  가격이 떨어지지 않은 시간은 몇 초인지를 출력하는 문제다.

 


- 풀이

#include <string>
#include <vector>
#include <queue>
// #include <iostream>

using namespace std;

vector<int> solution(vector<int> prices) {
    vector<int> answer(prices.size(),0);
    queue<pair<int,int>> q;
    int size, temp, idx;
    
    for(int i = 0; i < prices.size(); i++){
        q.push(pair<int,int>(prices[i],0));
        size = q.size();
        for(int j = 0; j < size; j++){
            temp = q.front().first;
            idx = q.front().second;
            q.pop();
            // cout << i << ' ' << j << ' ' << temp << ' ' << idx << '\n';
            if(temp > prices[i]){
                // cout << i << ' ' << j << ' ' << temp << ' ' << idx << "hahahahaha\n";
                answer[i - idx] = idx;
            }
            else
                q.push(pair<int,int>(temp, idx + 1));
        }
        
    }
    while(!q.empty()){
        temp = q.front().first;
        idx = q.front().second;
        q.pop();
        answer[prices.size() - idx] = idx - 1;
    }
    
    return answer;
}

 

 

스택을 이용해서 순서대로 하나씩 추가해주다가, 주식가격이 떨어지는 순서가 있으면 그 순서는 거기서 멈춰주면 된다.

 

  


- 기억할 것!

 X

반응형