🔗 주식가격
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; } }
'코딩테스트 > 문제풀이' 카테고리의 다른 글
[ 프로그래머스 ] #76502 : 괄호 회전하기 - JAVA (1) | 2025.03.31 |
---|---|
[ etc ] #9 : 10진수를 2진수로 변환하기 - JAVA (0) | 2025.03.23 |
[ 프로그래머스 ] #17684 : [3차] 압축 - JAVA (0) | 2025.02.05 |
[ 프로그래머스 ] #17683 : [3차] 방금그곡 - JAVA (0) | 2025.01.25 |
[ 프로그래머스 ] #17680 : [1차] 캐시 - JAVA (1) | 2025.01.21 |