[프로그래머스] 42584번 : 주식가격
코드
import java.util.Arrays;
import java.util.Stack;
public class PRO_42584 {
public static int[] solution(int[] prices) {
int[] answers = new int[prices.length];
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < answers.length; i++) {
while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
answers[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
}
while (!stack.isEmpty()) {
answers[stack.peek()] = prices.length - stack.peek() - 1;
stack.pop();
}
return answers;
}
public static void main(String[] args) {
int[] prices = {1, 2, 3, 2, 3};
System.out.println(Arrays.toString(solution(prices)));
}
}
풀이 및 느낀점
while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) {
answers[stack.peek()] = i - stack.peek();
stack.pop();
}
stack.push(i);
while문의 목적은 주식이 감소하는 구간을 찾기 위함이다.
현 위치의 값(prices[i])이 이전 위치의 값보다 작다면, answers[이전 위치 인덱스]에 <현위치 인덱스(i) - 이전위치 인덱스>를 저장해주면 된다.
그 다음, 스택에 저장된 최근 값(이전 위치 인덱스)을 빼주면 된다. while문을 벗어나면(감소구간이 종료되면), 현위치의 인덱스(i)를 스택에 저장했다.
while (!stack.isEmpty()) {
스택에 남아있는 값은 끝까지 감소구간이 없었다는 뜻이다. 그러므로 전체길이에서 해당 인덱스의 값을 빼주면 지속구간의 길이를 구할 수 있다.
참고자료
Author And Source
이 문제에 관하여([프로그래머스] 42584번 : 주식가격), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@doeunllee/프로그래머스-42584번-주식가격저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)