[Leetcode] 2110. Number of Smooth Descent Periods of a Stock

RexiaN·2025년 12월 15일

주식의 가격이 들어있는 배열이 주어지고 완만하게 감소하는 구간(1씩 감소하는 구간)을 구하는 문제. 원소 하나만 있는 부분배열도 1로 친다고 주어지므로 길이에 따른 등차수열의 공차가 1인 구간의 합을 계산하면 된다.

공식은 n*(n+1)/2 이므로 길이를 잰 후 공식을 더해주면 정답.

function getDescentPeriods(prices: number[]): number {
    let i = 0;
    let answer = 0;
    let smooth = 1;

    while(i < prices.length) {
        if ((i + 1) < prices.length) {
            const current = prices[i]
            const next = prices[i + 1]

            if (current === next + 1) {
                smooth += 1;
            } else {
                answer += ((smooth * (smooth + 1)) / 2)
                smooth = 1;
            }
        } else {
            answer += ((smooth * (smooth + 1)) / 2)
        }

        i += 1;
    }

    return answer;
};

profile
Don't forget Rule No.1

0개의 댓글