DDSA Solutions

2110. Number of Smooth Descent Periods of a Stock

Time: O(n)
Space: O(1)
Advertisement

Approach

Count consecutive descent run lengths; each run of length k contributes k*(k+1)/2.

Key Techniques

Array

Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.

Dynamic Programming

Dynamic programming solves problems by breaking them into overlapping sub-problems and storing results to avoid redundant work. The key steps are: define state, write a recurrence relation, set base cases, and choose top-down (memoization) or bottom-up (tabulation). DP often yields O(n²) → O(n) time improvements over brute force.

2110.cs
C#
// Approach: Count consecutive descent run lengths; each run of length k contributes k*(k+1)/2.
// Time: O(n) Space: O(1)

public class Solution
{
    public long GetDescentPeriods(int[] prices)
    {
        long totalDescentPeriods = 0;
        int arrayLength = prices.Length;

        int startIndex = 0;
        while (startIndex < arrayLength)
        {
            int endIndex = startIndex + 1;

            while (endIndex < arrayLength && prices[endIndex - 1] - prices[endIndex] == 1)
                endIndex++;

            int sequenceLength = endIndex - startIndex;

            totalDescentPeriods += (1L + sequenceLength) * sequenceLength / 2;

            startIndex = endIndex;
        }

        return totalDescentPeriods;
    }
}
Advertisement
Was this solution helpful?