메모리: 72.4 MB, 시간: 42.60 ms
코딩테스트 연습 > 스택/큐
정확성: 66.7
효율성: 33.3
합계: 100.0 / 100.0
2025년 11월 15일 18:25:39
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
| prices | return |
|---|---|
| [1, 2, 3, 2, 3] | [4, 3, 1, 1, 0] |
※ 공지 - 2019년 2월 28일 지문이 리뉴얼되었습니다.
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
문제 풀이
간단한 문제다. 지금 들어오는 항목과 과거 항목들을 비교하면서 진행해야 하기 때문에 굳이 O(N^2) 일 필요가 없다. 스택 자료구조로 간단히 구현했다.

코드
import java.util.*;
class Node {
int idx, price;
public Node(int idx, int price) {
this.idx = idx;
this.price = price;
}
}
class Solution {
public int[] solution(int[] prices) {
int n = prices.length;
int[] res = new int[n];
Stack<Node> stack = new Stack<>();
stack.push(new Node(0, prices[0]));
for(int i=1; i<n; i++){
while(!stack.isEmpty() && stack.peek().price > prices[i]){
Node n1 = stack.pop();
res[n1.idx] = i - n1.idx;
}
stack.push(new Node(i, prices[i]));
}
while(!stack.isEmpty()){
Node n2 = stack.pop();
res[n2.idx] = (prices.length - 1) - n2.idx;
}
// System.out.println(Arrays.toString(res));
return res;
}
}