2026.08.14
소요 시간: 37분
시간 복잡도:
import java.util.Deque;
import java.util.ArrayDeque;
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Deque<int[]> stack = new ArrayDeque<>();
int cnt = -1;
for (int i = 0; i < prices.length; i++) {
cnt++;
while(!stack.isEmpty() && stack.peek()[1] > prices[i]) {
int[] s = stack.pop();
answer[s[0]] = cnt - s[0];
}
stack.push(new int[]{i, prices[i]});
}
while(!stack.isEmpty()) {
int[] s = stack.pop();
answer[s[0]] = cnt - s[0];
}
return answer;
}
}
시간 복잡도:
코드 분석
전체적인 알고리즘은 동일하나, cnt를 사용하지 않고 i로 대체,
값을 저장하지 않고, 인덱스만 저장하여 prices[stack.peek()]로 대체하여
코드의 불필요한 변수 사용을 줄였다.
class Solution {
public int[] solution(int[] prices) {
int n = prices.length;
int[] answer = new int[n];
int[] stack = new int[n]; // 아직 가격이 떨어지지 않은 시점들의 인덱스
int top = -1;
for (int i = 0; i < n; i++) {
// i초에 가격이 떨어졌다면, 그보다 비쌌던 시점들은 여기서 기간 확정
while (top >= 0 && prices[stack[top]] > prices[i]) {
int j = stack[top--];
answer[j] = i - j;
}
stack[++top] = i;
}
// 끝까지 떨어지지 않은 시점들
while (top >= 0) {
int j = stack[top--];
answer[j] = n - 1 - j;
}
return answer;
}
}
대체 가능한 필요없는 변수를 정리해서
해당 작업을 거친 AI 코드는 훨씬 길이가 짧고 가독성이 좋다.
코드 작성 후에 깔끔하게 마무리 하는 습관을 들여야 할 것 같다.