문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때,
가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한사항
prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
prices의 길이는 2 이상 100,000 이하입니다.
입출력 예
prices return
[1, 2, 3, 2, 3] [4, 3, 1, 1, 0]
나는 처음에 문제를 이해하기가 어려웠다. 이제 접근법은 처음보고 이해가 안되면 검색하기로 그래서 모든 블로그를 검색해서 문제를 이해한 글을 살펴보고 이해했다.
블로그를 보고 기억해서 보지않고 타이핑을 쳐서 문제를 풀어보았다.
매일 이렇게 하다보니 조금 감이 잡힌 듯 하다.
import java.util.*;
class Solution {
public static int[] solution(int[] prices) {
int[] answer = new int[prices.length];
for(int i =0; i<prices.length;i++){
int cnt = 0;
for(int j=i+1; j<prices.length;j++){
cnt++;
if(prices[i] > prices[j]){
break;
}
}
answer[i] = cnt;
}
return answer;
}
}
통과하였다. 그렇지만 문제에서 원하는건 스택이므로 스택으로 풀어보기로 했다.
스택은 오히려 어려웠다. 스택풀이를 봤는데, 스택에 넣는 요소를 Integer 타입 행렬로 넣고 있는 풀이를 보았는데 오히려 더 어지러워져 클래스 하나를 넣고 비교하는게 나은 것 같았다.
import java.util.Stack;
public class StockPriceStackSolution {
public static int[] solution(int[] prices) {
int[] answer = new int[prices.length];
Stack<Stock> stack = new Stack<Stock>();
for(int i =0; i< prices.length; i++){
while(!stack.isEmpty() && stack.peek().price > prices[i]){
Stock j = stack.pop();
answer[j.time] = i - j.time;
}
stack.push(new Stock(prices[i],i));
}
while(!stack.isEmpty()){
Stock j = stack.pop();
answer[j.time] = prices.length - j.time-1;
}
return answer;
}
}
class Stock{
int time;
int price;
Stock(int price, int time){
this.price = price;
this.time = time;
}
}
이건 오히려 반복문이 더 쉬웠던거 같다.
시간을 많이 잡아 먹어서 스트레스를 받긴 했는데, 좀 더 자료구조에 대해서 파악이 필요하다.
https://ju-nam2.tistory.com/35 주남2 Blog
https://velog.io/@wan088 wani Blog 프로그래머스-고득점Kit-2-스택큐
https://velog.io/@godori/banner-maker-update GODORI
https://banner.godori.dev/ 배너생성기