DuckingRacoon
프로그래머스 | 주식 가격 본문
출처
문제
문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한사항
- prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
- prices의 길이는 2 이상 100,000 이하입니다.
입출력 예시
prices return
| [1, 2, 3, 2, 3] | [4, 3, 1, 1, 0] |
풀이
1차 풀이
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> prices)
{
stack<int> seconds;
vector<int> answer(prices.size(), 0);
int i = 0;
seconds.push(i);
while ( !(seconds.empty() && i >= prices.size()-1) )
{
if ( ( seconds.empty() || prices[seconds.top()] <= prices[i]) && i < prices.size() - 1)
{
seconds.push(i);
i++;
}
else
{
answer[seconds.top()] = i - seconds.top();
seconds.pop();
}
}
return answer;
}
GPT 풀이
#include <string>
#include <vector>
#include <stack>
using namespace std;
vector<int> solution(vector<int> prices)
{
stack<int> indices;
vector<int> answer(prices.size(), 0);
for (int i = 0; i < prices.size(); i++)
{
// Process and calculate the duration for indices in the stack
while (!indices.empty() && prices[indices.top()] > prices[i])
{
int top = indices.top();
indices.pop();
answer[top] = i - top;
}
indices.push(i);
}
// Handle remaining indices where the price never dropped
while (!indices.empty())
{
int top = indices.top();
indices.pop();
answer[top] = prices.size() - 1 - top;
}
return answer;
}
- while문의 조건 복잡하지 않게!()
- stack -1 넣기
'알고리즘' 카테고리의 다른 글
| 프로그래머스 | 이중우선순위큐 (0) | 2025.09.03 |
|---|---|
| 프로그래머스 | 디스크 컨트롤러 (0) | 2025.09.03 |
| 프로그래머스 | [연습문제] 프로세스 (1) | 2025.09.01 |
| 프로그래머스 | [연습문제] 올바른 괄호 (1) | 2025.09.01 |
| 프로그래머스 | [연습문제] 기능개발 (0) | 2025.09.01 |