초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
prices | return |
---|---|
[1, 2, 3, 2, 3] | [4, 3, 1, 1, 0] |
class Solution {
public int[] solution(int[] prices) {
int[] answer = new int[prices.length];
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
answer[i]++;
if (prices[i] > prices[j])
break;
}
}
return answer;
}
}
처음에 2중포문으로 문제를 해결했다 스택,큐와 관련된 문제인데 그 부분에 대한 이해가 너무 부족한 것 같아 찾아보고 다시 작성해 본 코드
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++) {
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;
}
}