프로그래머스 2레벨 42584 주식가격 JAVA

문제

링크 : https://programmers.co.kr/learn/courses/30/lessons/42584

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

풀이

문제에서 스택을 쓰라고하니 스택을 쓰는 것 까지는 ok인데..

분명 예전에 본 것 같은 문제인데도 풀이법이 잘 떠오르지 않았다.. 🙀

찾아보니 스택에 다음 값을 담는다고 생각하면 이해가 됐다.

일단 가장 높은 주식 가격의 인덱스가 항상 스택의 top에 있다.

1
stack.push(i);

만약 가장 높은 주식 가격이 붕괴됐다면 붕괴된 값은 빼주고 정답에 붕괴될 때까지 얼마나 걸렸는지 기록한다.

1
2
3
4
5
while( !(stack.empty()) && prices[stack.peek()] > prices[i])
{
int tmp = stack.pop();
answer[tmp] = i - tmp;
}

코드

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
import java.util.Stack;


class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stack = new Stack<Integer>();

for(int i=0;i<prices.length;i++)

{
while( !(stack.empty()) && prices[stack.peek()] > prices[i])
{
int tmp = stack.pop();
answer[tmp] = i - tmp;
}
stack.push(i);

}

while(!stack.empty())
{
int tmp = stack.pop();
answer[tmp] = prices.length - 1 - tmp;
}

return answer;
}


}

메모

스스로 풀었는가 : ❎

뭔가 아이디어가 생각나지 않아 풀지 못한 문제.. 능지 어떡함!!!😡

프로그래머스 2레벨 42584 주식가격 JAVA

https://praisebak.github.io/2021/07/15/2021-07/p42584/

Author

Praisebak

Posted on

2021-07-15

Updated on

2021-07-15

Licensed under

Comments