Skip to main content

Number of Smooth Descent Periods of a Stock - Solution & Explanation

MediumArrayMathDynamic Programming20 min readAsked at: Amazon, Microsoft, Google
Practice this problem

Problem Statement

You are given an integer array prices representing the daily price history of a stock, where prices[i] is the stock price on the ith 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.

 

Example 1:

Input: prices = [3,2,1,4]
Output: 7
Explanation: There are 7 smooth descent periods:
[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]
Note that a period with one day is a smooth descent period by the definition.

Example 2:

Input: prices = [8,6,7,7]
Output: 4
Explanation: There are 4 smooth descent periods: [8], [6], [7], and [7]
Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.

Example 3:

Input: prices = [1]
Output: 1
Explanation: There is 1 smooth descent period: [1]

 

Constraints:

  • 1 <= prices.length <= 105
  • 1 <= prices[i] <= 105

Approach Overview

Problem Overview: You receive an integer array prices representing the daily stock price. A smooth descent period is a contiguous subarray where each element is exactly 1 less than the previous element. Every single element also counts as a valid period. The goal is to count the total number of such periods across the entire array.

Approach 1: Using a Stack (O(n) time, O(n) space)

This approach tracks the current descent sequence using a stack. Iterate through the array and compare each price with the previous value. If prices[i] == prices[i-1] - 1, the descent continues, so push the value onto the stack and increase the running count by the current stack size. If the condition breaks, reset the stack because the descent sequence ends and a new one begins. The key insight: every extension of a valid descent sequence creates multiple new subarrays ending at the current index. The stack effectively stores the active decreasing run. This approach is intuitive when reasoning about contiguous patterns in array traversal and makes it easy to visualize how subarrays expand.

Approach 2: Recursive Evaluation (O(n) time, O(n) space)

The recursive method evaluates the length of the descent sequence starting at each index. If prices[i+1] == prices[i] - 1, the sequence extends and the recursion continues to the next index. Otherwise, the recursion terminates and returns 1 because a single element still forms a valid descent period. Memoization stores previously computed results to avoid recomputation, turning the recursion into a top‑down dynamic programming solution. Each recursive call calculates how many valid subarrays start at that position, and the final answer sums all results. The logic closely mirrors the mathematical definition of the descent rule and works well when modeling state transitions.

Both methods rely on the same observation: if a descending run has length k, it contributes k * (k + 1) / 2 valid subarrays. Recognizing this pattern simplifies counting and connects the solution to basic math reasoning about sequences.

Recommended for interviews: The linear scan approach implemented with stack-like tracking is what most interviewers expect. It processes the array once, maintains a running descent length, and accumulates counts in O(n) time. The recursive formulation shows deeper understanding of the state transition and can help explain the dynamic programming structure, but iterative O(n) traversal demonstrates stronger practical optimization skills.

Approach 1: Approach 1: Using a Stack

This approach uses a stack to efficiently manage and track data as we process it. Stacks are last-in, first-out (LIFO) data structures that allow us to handle nested or hierarchical data effectively, such as the problem of parsing or evaluating expressions.

This C solution uses a custom stack implementation to evaluate a simple postfix expression. The stack is used to store operands, and operators are applied to the operands popped from the stack. The result is pushed back onto the stack. The final result is obtained by popping the stack after all operations are done.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), Space Complexity: O(n), where n is the length of the expression.

Try this approach in the editor β†’

Approach 2: Approach 2: Recursive Evaluation

This approach utilizes recursion to evaluate the expression. Recursive functions are a profound way to break down complex problems into simpler instances of the same problem. Here, recursion helps by breaking the expression into parts that can be independently processed.

This C solution uses a recursive function to evaluate expressions. The function continuously evaluates parts of the expression by calling itself. This makes it a direct, elegant solution for nested or compound expressions.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), Space Complexity: O(n), where n is the depth of the recursion, potentially bound by the length of the expression.

Try this approach in the editor β†’

Approach 3: Two Pointers

We define an answer variable ans with an initial value of 0.

Next, we use two pointers i and j, which point to the first day of the current smooth descent period and the day after the last day, respectively. Initially, i = 0 and j = 0.

We traverse the array prices from left to right. For each position i, we move j to the right until j reaches the end of the array or prices[j - 1] - prices[j] neq 1. At this point, cnt = j - i is the length of the current smooth descent period, and we add \frac{(1 + cnt) times cnt}{2} to the answer variable ans. Then we update i to j and continue traversing.

After the traversal ends, we return the answer variable ans.

The time complexity is O(n), where n is the length of the array prices. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Approach 1: Using a Stack

Time Complexity: O(n), Space Complexity: O(n), where n is the length of the expression.

Approach 2: Recursive Evaluation

Time Complexity: O(n), Space Complexity: O(n), where n is the depth of the recursion, potentially bound by the length of the expression.

Two Pointersβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Stack-based Descent TrackingO(n)O(n)Best general solution for scanning arrays and counting valid descent segments efficiently
Recursive Evaluation with MemoizationO(n)O(n)Useful for demonstrating dynamic programming reasoning or recursive state transitions

Video Solution

Number of Smooth Descent Periods of a Stock | Simple Approach | Leetcode 2110 | codestorywithMIK β€’ codestorywithMIK β€’ 4,751 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Number of Smooth Descent Periods of a Stock easy or hard?
The problem is classified as Medium because the brute-force approach is straightforward but inefficient. The challenge is recognizing that consecutive decreasing sequences can be counted incrementally. Once the streak-counting insight is identified, the final algorithm becomes a simple O(n) array traversal.
Number of Smooth Descent Periods of a Stock Python/Java solution
Python and Java implementations typically iterate once through the prices array while maintaining a variable for the current descent length. When prices[i] == prices[i-1] - 1, increase the streak; otherwise reset it to 1. Add the streak to the total count each step, producing an O(n) time solution.
How to solve Number of Smooth Descent Periods of a Stock in O(n)?
Traverse the array once while keeping a variable that stores the current descent length. If the difference between consecutive prices is exactly -1, increment the streak; otherwise reset it to 1. Add the streak length to the total at every step because each extension forms additional valid subarrays ending at that index.
What is the best approach for Number of Smooth Descent Periods of a Stock?
The best approach is a linear scan that tracks the current smooth descent length while iterating through the array. If prices[i] equals prices[i-1] - 1, extend the current streak and add its length to the total count. Otherwise reset the streak to 1. This runs in O(n) time and requires O(1) or O(n) auxiliary space depending on implementation.
Is Number of Smooth Descent Periods of a Stock asked at Google/Amazon/Meta?
Array pattern counting and sequence analysis problems like this frequently appear in interviews at companies such as Amazon, Google, and Meta. The question tests recognition of consecutive patterns and efficient subarray counting. Interviewers typically expect an O(n) traversal rather than brute force.
What data structure is used in Number of Smooth Descent Periods of a Stock?
The core structure is a simple array traversal. Some implementations use a stack to track the active descending sequence, while others maintain a running counter representing the current descent length. The recursive variant models the logic using dynamic programming with memoization.
What is the time complexity of Number of Smooth Descent Periods of a Stock?
The optimal solution runs in O(n) time because the algorithm processes each price exactly once while maintaining the current descent streak. Brute-force enumeration of all subarrays would take O(n^2), but the streak counting technique avoids rechecking elements. Space complexity is O(1) for iterative implementations or O(n) if recursion with memoization is used.

Ready to solve this problem?

Practice Number of Smooth Descent Periods of a Stock with our built-in code editor and test cases.

Practice on FleetCode