Search
Duplicate
📒

[Programmers] 02-3. 주식가격 ⭐

상태
완료
수업
Algorithm Solving
주제
Programmers
4 more properties
참고

문제해설

NOTE
입력 값 ⇒ prices (1차원 정수배열 )
출력 값 ⇒ prices의 각 요소가 가격이 떨어지지 않은 기간

문제 로직고민

NOTE
Stack, Queue를 사용하는 방법을 고민해봤는데 방법이 떠오르지 않았다.
가장 무식한 방법인 n^2탐색으로 먼저 진행했다.

작성코드

NOTE
import java.util.*; class Solution { public int[] solution(int[] prices) { int[] answer = new int[prices.length]; for(int i=0; i<prices.length-1; i++){ for(int j = i+1; j < prices.length; j++ ){ answer[i]++; if(prices[i] > prices[j]) break; } } return answer; } }
Java
복사
풀이시간 : 16분

다른사람 풀이

NOTE
import java.util.Stack; class Solution { public int[] solution(int[] prices) { int[] answer = new int[prices.length]; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < prices.length; i++) { // Stack이 비어있지 않고, 다음 숫자가 더 작다면 while (!stack.isEmpty() && prices[i] < prices[stack.peek()]) { answer[stack.peek()] = i - stack.peek(); stack.pop(); } stack.push(i); } while (!stack.isEmpty()) { answer[stack.peek()] = prices.length - stack.peek() - 1; stack.pop(); } return answer; } }
Java
복사
Stack 사용코드