코딩테스트
프로그래머스 주식가격(자바) - 스택**
leeeehhjj
2022. 4. 7. 14:30
처음에는 스택에 prices 배열을 모두 넣은 후에 하나씩 pop 하고 남은 요소들을 for문으로 탐색하려고 했는데 계속 원하는 값이 안 나와서 다른 블로그를 참고했다.
[프로그래머스] 주식가격(Stack) - JAVA :: 그냥 그냥 블로그 (tistory.com)
[프로그래머스] 주식가격(Stack) - JAVA
문제 링크 [프로그래머스] 주식가격 코딩테스트 연습 - 주식가격 초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 s
girawhale.tistory.com
import java.util.*;
class Stack_4 {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < prices.length; i++) {
while(!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
answer[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
while(!stack.isEmpty()) {
answer[stack.peek()] = prices.length - 1 - stack.peek();
stack.pop();
}
return answer;
}
}