#2110
Number of Smooth Descent Periods of a Stock
MediumArrayMathTwo PointersDynamic ProgrammingSliding WindowTwo PointersSliding WindowDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a single pass through the array to count smooth descent periods by leveraging the relationship between consecutive days. This reduces the time complexity significantly.
⚙️
Algorithm
6 steps- 1Step 1: Initialize a count variable to store the total number of smooth descent periods.
- 2Step 2: Initialize a variable to track the length of the current smooth descent period.
- 3Step 3: Iterate through the prices array starting from the second element.
- 4Step 4: If the current price is exactly 1 less than the previous price, increment the current period length.
- 5Step 5: If not, reset the current period length to 0.
- 6Step 6: Add the current period length to the total count.
solution.py11 lines
1# Full working Python code
2prices = [3, 2, 1, 4]
3count = len(prices)
4current_period_length = 0
5for i in range(1, len(prices)):
6 if prices[i] == prices[i - 1] - 1:
7 current_period_length += 1
8 count += current_period_length
9 else:
10 current_period_length = 0
11print(count)ℹ
Complexity note: This complexity is achieved because we only traverse the array once, making it much more efficient than the brute-force approach.
- 1Smooth descent periods can overlap, and each single day is a valid period.
- 2Tracking the length of the current descent allows us to efficiently count all periods.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.