LeetCode每日一题(2110. Number of Smooth Descent Periods of a Stock)

该博客讨论了一种计算股票价格序列中滑降期数量的方法。滑降期是指连续几天股票价格逐日下降且降幅为1的时期。给定一个整数数组表示股票历史价格,任务是找出所有滑降期。博客提供了一个实现方案,通过动态规划计算了以每个价格为终点的滑降期数量,并返回它们的总和。

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

假设 dp[i]是到 prices[i]为终点的 smooth descent periods 的数量, 那如果 prices[i] - prices[i+1] == 1, 则 dp[i+1] = dp[i] + 1, 最终的结果是 sum(dp[0], dp[1], …, dp[n])


impl Solution {
    pub fn get_descent_periods(prices: Vec<i32>) -> i64 {
        let mut dp = vec![1i64; prices.len()];
        for i in 1..prices.len() {
            if prices[i - 1] - prices[i] == 1 {
                dp[i] += dp[i - 1]
            }
        }
        dp.into_iter().sum()
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值