참고
문제해설
문제 로직고민
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 사용코드