|
| 1 | +# [Problem 2110: Number of Smooth Descent Periods of a Stock](https://leetcode.com/problems/number-of-smooth-descent-periods-of-a-stock/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +I’m sorry — I can’t share my internal chain-of-thought. Instead, here is a concise summary of the approach: |
| 5 | + |
| 6 | +- We want to count all contiguous subarrays where each day (except the first in the subarray) is exactly 1 less than the previous day. |
| 7 | +- Equivalent observation: split the array into maximal runs where each adjacent pair differs by -1. For a run of length L, the number of contiguous subarrays inside it is L*(L+1)/2. |
| 8 | +- We can compute this in one pass by maintaining the current run length and adding it to the answer at each step. |
| 9 | + |
| 10 | +## Refining the problem, round 2 thoughts |
| 11 | +Refinements and edge considerations (concise): |
| 12 | +- A single day always counts (run length at least 1). |
| 13 | +- When prices[i-1] - prices[i] == 1, extend the current run; otherwise start a new run of length 1. |
| 14 | +- Sum run-length contributions incrementally to avoid storing runs explicitly. |
| 15 | +- Time complexity O(n), space O(1) beyond input. |
| 16 | +- Handle n up to 1e5 — one pass is fine; use 64-bit integer for the answer since sum can be ~ n*(n+1)/2. |
| 17 | + |
| 18 | +## Attempted solution(s) |
| 19 | +```python |
| 20 | +class Solution: |
| 21 | + def numberOfSmoothDescentPeriods(self, prices: list[int]) -> int: |
| 22 | + # current run length (at least 1 for the current day) |
| 23 | + cur_len = 1 |
| 24 | + ans = 0 |
| 25 | + for i in range(1, len(prices)): |
| 26 | + if prices[i-1] - prices[i] == 1: |
| 27 | + cur_len += 1 |
| 28 | + else: |
| 29 | + # add all subperiods contributed by the previous run |
| 30 | + ans += cur_len * (cur_len + 1) // 2 |
| 31 | + cur_len = 1 |
| 32 | + # add the last run |
| 33 | + ans += cur_len * (cur_len + 1) // 2 |
| 34 | + return ans |
| 35 | +``` |
| 36 | +- Notes: |
| 37 | + - This implementation groups contiguous days where consecutive differences equal -1 into runs. For each run of length L, there are L*(L+1)/2 smooth descent periods. |
| 38 | + - Time complexity: O(n), where n = len(prices). |
| 39 | + - Space complexity: O(1) extra space. |
| 40 | + - Uses integer arithmetic; final answer fits in Python int (arbitrary precision). |
0 commit comments