Number of Smooth Descent Periods of a Stock - Problem
Stock Market Analysis Challenge!
You're a financial analyst tracking stock price movements. Given an array
A smooth descent period is a sequence of consecutive days where:
• Each day's price is exactly 1 unit lower than the previous day
• The first day of any period doesn't need to follow this rule
• Even a single day counts as a period of length 1
Goal: Count the total number of smooth descent periods in the stock's price history.
Example: For prices
You're a financial analyst tracking stock price movements. Given an array
prices where prices[i] represents the stock price on day i, you need to identify all smooth descent periods.A smooth descent period is a sequence of consecutive days where:
• Each day's price is exactly 1 unit lower than the previous day
• The first day of any period doesn't need to follow this rule
• Even a single day counts as a period of length 1
Goal: Count the total number of smooth descent periods in the stock's price history.
Example: For prices
[3, 2, 1, 4], we have periods: [3], [3,2], [3,2,1], [2], [2,1], [1], [4] = 7 periods total. Input & Output
example_1.py — Basic Descent
$
Input:
prices = [3, 2, 1, 4]
›
Output:
7
💡 Note:
Smooth descent periods: [3] (1), [3,2] (1), [3,2,1] (1), [2] (1), [2,1] (1), [1] (1), [4] (1). Total = 7 periods.
example_2.py — No Descent
$
Input:
prices = [1, 2, 3, 4]
›
Output:
4
💡 Note:
No smooth descents possible. Each single day forms its own period: [1], [2], [3], [4]. Total = 4 periods.
example_3.py — Single Element
$
Input:
prices = [4]
›
Output:
1
💡 Note:
Only one element, which forms exactly one smooth descent period of length 1.
Visualization
Tap to expand
Understanding the Visualization
1
Track Current Run
Keep track of how long our current smooth descent is
2
Extend or Reset
If the next price is exactly 1 less, extend the run; otherwise start fresh
3
Count All Routes
Each time we extend, we create one new ski route ending at this point
Key Takeaway
🎯 Key Insight: Each time we extend a smooth descent by one position, we create exactly one new descent period while preserving all existing ones. This allows us to count efficiently in O(n) time!
Time & Space Complexity
Time Complexity
O(n)
Single pass through the array, each element processed once
✓ Linear Growth
Space Complexity
O(1)
Only using a few variables to track state
✓ Linear Space
Constraints
- 1 ≤ prices.length ≤ 105
- 1 ≤ prices[i] ≤ 109
- Each price is a positive integer
- Array contains at least one element
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code