Number of Smooth Descent Periods of a Stock — LeetCode 2110 Python Solution
- Problem
- #2110
- Pattern
- Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The 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 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.
Example
- Input
- prices = [3,2,1,4]
- Output
- 7
- Explanation
- There are 7 smooth descent periods:
Python solution
class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
ans = 0
i, n = 0, len(prices)
while i < n:
j = i + 1
while j < n and prices[j - 1] - prices[j] == 1:
j += 1
cnt = j - i
ans += (1 + cnt) * cnt // 2
i = j
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{prices} |
| Space | O(1) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2110. Number of Smooth Descent Periods of a Stock is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2110. Number of Smooth Descent Periods of a Stock?
- LeetCode 2110. Number of Smooth Descent Periods of a Stock is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2110. Number of Smooth Descent Periods of a Stock?
- The Python solution on this page runs in O(n), where n is the length of the array \textit{prices}.
- What is the space complexity of LeetCode 2110. Number of Smooth Descent Periods of a Stock?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2110. Number of Smooth Descent Periods of a Stock cover?
- LeetCode 2110. Number of Smooth Descent Periods of a Stock is tagged Array, Math, Two Pointers, Dynamic Programming and Sliding Window on LeetCode.