Number of Smooth Descent Periods of a Stock - Problem

You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the i-th day.

A smooth descent period of a stock consists of one or more contiguous days such that the price on each day is lower than the price on the preceding day by exactly 1. The first day of the period is exempted from this rule.

Return the number of smooth descent periods.

Input & Output

Example 1 — Basic Descent
$ Input: prices = [3,2,1,4]
Output: 7
💡 Note: Smooth descent periods: [3], [2], [1], [4], [3,2], [2,1], [3,2,1]. Each single element forms a period, plus [3,2] (3→2 drops by 1), [2,1] (2→1 drops by 1), and [3,2,1] (both transitions drop by 1).
Example 2 — No Multi-Element Descents
$ Input: prices = [8,6,7,7]
Output: 4
💡 Note: Only single-element periods: [8], [6], [7], [7]. No multi-element descents since 8→6 drops by 2 (not 1), 6→7 increases, 7→7 stays same.
Example 3 — Long Descent
$ Input: prices = [1]
Output: 1
💡 Note: Single element [1] forms one descent period.

Constraints

  • 1 ≤ prices.length ≤ 105
  • 1 ≤ prices[i] ≤ 109

Visualization

Tap to expand
Number of Smooth Descent Periods INPUT prices array 3 i=0 2 i=1 1 i=2 4 i=3 Price Trend 3 2 1 4 Smooth descent (-1) Break [3,2,1] forms smooth descent ALGORITHM STEPS 1 Initialize dp[i] = length of descent ending at index i 2 Check Condition If prices[i-1] - prices[i] == 1 then dp[i] = dp[i-1] + 1 3 Otherwise dp[i] = 1 (single day period) 4 Sum All Result = sum(dp[i]) DP Table i 0 1 2 3 prices 3 2 1 4 dp[i] 1 2 3 1 Sum: 1 + 2 + 3 + 1 = 7 FINAL RESULT All Smooth Descent Periods Period 1: [3] - single day Period 2: [2] - single day Period 3: [1] - single day Period 4: [4] - single day Period 5: [3,2] - 2 days Period 6: [2,1] - 2 days Period 7: [3,2,1] - 3 days Output 7 Key Insight: Each dp[i] counts all smooth descent periods ending at index i. If prices[i-1] - prices[i] = 1, then dp[i] = dp[i-1] + 1 (extending all previous periods + new single day). Otherwise dp[i] = 1. Time: O(n), Space: O(1) - we only need previous dp value, not the entire array! TutorialsPoint - Number of Smooth Descent Periods of a Stock | Dynamic Programming Approach
Asked in
Google 25 Amazon 18 Facebook 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen