[ 프로그래머스 ] #42584 : 주식가격 - JAVA

🔗 주식가격

import java.util.*;
class Solution {
public int[] solution(int[] prices) {
int n = prices.length;
int[] answer = new int[n];
Stack<Integer> stack = new Stack<>(); // 인덱스를 저장할 스택
for (int i = 0; i < n; i++) {
// 스택이 비어있지 않고, 현재 가격이 스택의 최상단 가격보다 낮다면 가격이 떨어진 것
while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
int idx = stack.pop();
answer[idx] = i - idx; // 가격이 떨어진 시점 - 처음 가격이 유지된 시점
}
stack.push(i); // 현재 인덱스를 스택에 저장
}
// 스택에 남아있는 인덱스는 끝까지 가격이 떨어지지 않은 경우
while (!stack.isEmpty()) {
int idx = stack.pop();
answer[idx] = n - 1 - idx; // 끝까지 유지된 시간
}
return answer;
}
}