스택을 이용해서 푸는 문제이다. 쉬웠는데 딱 한가지 실수는 while 문에서 !stack.isEmpty() 를 넣어주지 않아서 런타임 에러가 발생했다. while문을 돌면서 스택에 값이 모두 빠져 비어있는 경우에도 while문을 돌 수 있기 때문에 !stack.isEmpty() 를 잊지말고 꼭 넣어주자!
import java.util.*;
class Solution {
public int[] solution(int[] prices) {
Stack<Integer> stack = new Stack<>();
int[] answer = new int[prices.length];
for (int i = 0; i < prices.length; i++) {
if (stack.isEmpty()) {
stack.push(i);
continue;
}
while (!stack.isEmpty() && prices[stack.peek()] > prices[i]) {
int idx = stack.pop();
answer[idx] = i - idx;
}
stack.push(i);
}
while (!stack.isEmpty()) {
int idx = stack.pop();
answer[idx] = prices.length - 1 - idx;
}
return answer;
}
}
'CS > Algorism' 카테고리의 다른 글
99클럽 코테 스터디 6일차 TIL: [프로그래머스] 이중우선순위큐 (0) | 2024.05.25 |
---|---|
99클럽 코테 스터디 5일차 TIL: [프로그래머스] 디스크 컨트롤러 (0) | 2024.05.24 |
[백준] 12865. 평범한 배낭 (0) | 2024.05.23 |
99클럽 코테 스터디 3일차 TIL: [프로그래머스] 다리를 지나는 트럭 (0) | 2024.05.22 |
99클럽 코테 스터디 2일차 TIL: [백준] 2179. 비슷한 단어 (0) | 2024.05.21 |