스택 문제 (프로그래머스 : 주식가격)
문제 설명
초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
제한사항
prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
prices의 길이는 2 이상 100,000 이하입니다.
나의 풀이
function solution(prices) {
var answer = [];
let arrLength = prices.length;
for (let i = 0; i < prices.length; i++) {
// 마지막 요소는 다음 비교군이 없으므로 0으로 끝
if (i === arrLength - 1) {
answer.push(0);
}
// 마지막 요소가 아닌경우
else {
let h = i + 1;
let count = 0;
while (h > 0 && h < arrLength) {
// 다음 요소와 비교해서 , 다음요소가 크거나 같을 경우 줄어들지 않음
if (prices[i] <= prices[h]) {
count++;
if (h === arrLength - 1) {
answer.push(count);
break;
}
h++;
} else {
count++;
answer.push(count);
h = 0;
}
}
}
}
return answer;
}
console.log(solution([1, 2, 3, 2, 3]));
GPT의 풀이 및 개선해야할 점
풀이방향
=> O(n) 의 시간 복잡도를 가진다.
But, 나의 풀이는 O(n2)의 시간복잡도를 가지기에 효율적이지는 못하다.
function solution(prices) {
const answer = Array(prices.length).fill(0);
const stack = [];
for (let i = 0; i < prices.length; i++) {
while (stack.length > 0 && prices[stack[stack.length - 1]] > prices[i]) {
const top = stack.pop();
answer[top] = i - top;
}
stack.push(i);
}
while (stack.length > 0) {
const top = stack.pop();
answer[top] = prices.length - top - 1;
}
return answer;
}
배울점