[프로그래머스] 주식가격

Jhanoo·2024년 8월 14일

알고리즘 스터디

목록 보기
9/80

문제

문제 설명

초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.

제한사항

prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
prices의 길이는 2 이상 100,000 이하입니다.


코드 풀이

StackInteger[0]: index, Integer[1]: price를 담는다.

  1. Stackprices[]를 넣는다.
  2. prices[i]를 넣을 때, stack.peek()으로 비교해서 먼저 넣은 값이 크면 pop()한 후 초 계산
  3. push가 끝난 후 stack이 비어있지 않으면 pop()하면서 초 계산.

작성한 코드

import java.util.Stack;

class Solution {
    
    public int[] solution(int[] prices) {
		int[] answer = new int[prices.length];
		Stack<Integer[]> stack = new Stack<Integer[]>();

		for (int i = 0; i < prices.length; i++) {

			while (!stack.isEmpty()) {
				if (stack.peek()[1] > prices[i]) {
					Integer[] t = stack.pop();
					answer[t[0]] = i - t[0];
				} else {
					break;
				}
			}
			stack.push(new Integer[] { i, prices[i] });
		}

		while (!stack.isEmpty()) {
			Integer[] t = stack.pop();
			answer[t[0]] = prices.length - t[0] - 1;
		}

		return answer;
	}
    
}
profile
최선을 다하자~~

0개의 댓글