2110. Number of Smooth Descent Periods of a Stock
MediumView on LeetCode
Time: O(n)
Space: O(1)
Problem Overview
Number of Smooth Descent Periods of a Stock (Medium) asks you to solve a structured algorithmic task. This is a common Array / Dynamic Programming pattern in coding interviews. Count consecutive descent run lengths; each run of length k contributes k*(k+1)/2.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Count consecutive descent run lengths; each run of length k contributes k*(k+1)/2.
Related patterns: Array, Dynamic Programming
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;
}
}Was this solution helpful?
Related Problems
- 63. Unique Paths II(Medium)
- 85. Maximal Rectangle(Hard)
- 118. Pascal's Triangle(Easy)
- 120. Triangle(Medium)
- 122. Best Time to Buy and Sell Stock II(Medium)
- 174. Dungeon Game(Hard)