본문 바로가기
개발/프로그래머스

스택/큐 > 주식가격 (Level2)

by 민돌이2 2021. 10. 30.

문제 설명

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

 

제한사항

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

 

입출력 예

prices return
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]

 

입출력 예 설명

  • 1초 시점의 ₩1은 끝까지 가격이 떨어지지 않았습니다.
  • 2초 시점의 ₩2은 끝까지 가격이 떨어지지 않았습니다.
  • 3초 시점의 ₩3은 1초뒤에 가격이 떨어집니다. 따라서 1초간 가격이 떨어지지 않은 것으로 봅니다.
  • 4초 시점의 ₩2은 1초간 가격이 떨어지지 않았습니다.
  • 5초 시점의 ₩3은 0초간 가격이 떨어지지 않았습니다.

 

소스코드

#include <string>
#include <vector>
#include <queue>

using namespace std;

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

	queue<int> datas;

	for (int i = 0; i < prices.size(); i++)
	{
		for (int j = i + 1; j < prices.size(); j++)
		{
			if (prices[i] > prices[j])
			{
				datas.push(j - i);

				break;
			}

			//마지막까지 검출되지 않았을 경우
			if (j >= (prices.size() - 1))
				datas.push(j - i);
		}
	}

	//마지막 원소는 비교대상이 없어 0 고정
	datas.push(0);

	while (datas.empty() == false)
	{
		answer.emplace_back(datas.front());
		datas.pop();
	}

	return answer;
}

 

생각해 볼 다른사람 코드

#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

댓글