LeetCode 题解工作台
股票平滑下跌阶段的数目
给你一个整数数组 prices ,表示一支股票的历史每日股价,其中 prices[i] 是这支股票第 i 天的价格。 一个 平滑下降的阶段 定义为:对于 连续一天或者多天 ,每日股价都比 前一日股价恰好少 1 ,这个阶段第一天的股价没有限制。 请你返回 平滑下降阶段 的数目。 示例 1: 输入: p…
3
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义一个答案变量 ,初始值为 。 接下来,我们使用双指针 和 ,分别指向当前平滑下降阶段的第一天和最后一天的下一天。初始时 $i = 0$, $j = 0$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 prices ,表示一支股票的历史每日股价,其中 prices[i] 是这支股票第 i 天的价格。
一个 平滑下降的阶段 定义为:对于 连续一天或者多天 ,每日股价都比 前一日股价恰好少 1 ,这个阶段第一天的股价没有限制。
请你返回 平滑下降阶段 的数目。
示例 1:
输入:prices = [3,2,1,4] 输出:7 解释:总共有 7 个平滑下降阶段: [3], [2], [1], [4], [3,2], [2,1] 和 [3,2,1] 注意,仅一天按照定义也是平滑下降阶段。
示例 2:
输入:prices = [8,6,7,7] 输出:4 解释:总共有 4 个连续平滑下降阶段:[8], [6], [7] 和 [7] 由于 8 - 6 ≠ 1 ,所以 [8,6] 不是平滑下降阶段。
示例 3:
输入:prices = [1] 输出:1 解释:总共有 1 个平滑下降阶段:[1]
提示:
1 <= prices.length <= 1051 <= prices[i] <= 105
解题思路
方法一:双指针
我们定义一个答案变量 ,初始值为 。
接下来,我们使用双指针 和 ,分别指向当前平滑下降阶段的第一天和最后一天的下一天。初始时 , 。
从左到右遍历数组 ,对于每个位置 ,我们将 向右移动,直到 到达数组末尾或者 为止。此时, 即为当前平滑下降阶段的长度,我们累加 到答案变量 中。接下来将 更新为 ,继续遍历。
遍历结束后,返回答案变量 即可。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
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 ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) since we iterate through the prices array once. Space complexity is O(1) because we only track current period length and total count without storing intermediate periods. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Focuses on consecutive differences of exactly 1 in array sequences.
- question_mark
Expect candidates to handle single-day periods correctly.
- question_mark
Wants an O(n) one-pass solution without extra arrays.
常见陷阱
外企场景- error
Resetting the period length incorrectly when difference is not exactly 1.
- error
Forgetting to include single-day periods in the total count.
- error
Miscounting overlapping sub-periods within longer smooth descent sequences.
进阶变体
外企场景- arrow_right_alt
Count smooth ascent periods where each day's price increases by 1.
- arrow_right_alt
Calculate maximum length of any smooth descent period instead of total count.
- arrow_right_alt
Handle circular arrays where the end connects back to the start for smooth descent.