theshy

博客园 首页 新随笔 联系 订阅 管理






dp[i]:以第i天为结尾,平滑下降阶段的数目
dp[i]=dp[i-1]+1(prices[i-1]-1==prices[i])
java

class Solution {
    public long getDescentPeriods(int[] prices) {
        //init
        int n = prices.length;
        int[] dp = new int[n];
        dp[0] = 1;
        long ans = 0;
        //dp
        for (int i = 1; i < n; i++) {
            dp[i] = (prices[i - 1] - 1 == prices[i]) ? dp[i - 1] + 1 : 1;
        }
        for (int i = 0; i < n; i++) {
            ans += dp[i];
        }
        return ans;
    }
}

python

from typing import List
class Solution:
    def getDescentPeriods(self, prices: List[int]) -> int:
        # init
        n = len(prices)
        dp = [0] * n
        dp[0] = 1
        ans = 0
        # dp
        for i in range(1, n):
            dp[i] = dp[i - 1] + 1 if (prices[i - 1] - 1 == prices[i]) else 1
        for i in range(0, n):
            ans += dp[i]
        return ans

js

/**
 * @param {number[]} prices
 * @return {number}
 */
var getDescentPeriods = function (prices) {
    let n = prices.length
    let dp = new Array(n)
    dp[0] = 1
    let ans = 0
    for (let i = 1; i < n; i++) {
        dp[i] = (prices[i - 1] - 1 == prices[i]) ? dp[i - 1] + 1 : 1
    }
    for (let i = 0; i < n; i++) {
        ans += dp[i]
    }
    return ans
};

c++

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    long long getDescentPeriods(vector<int> &prices) {
        int n = prices.size();
        int dp[n];
        dp[0] = 1;
        long long ans = 0;
        for (int i = 1; i < n; ++i) {
            dp[i] = prices[i - 1] - 1 == prices[i] ? dp[i - 1] + 1 : 1;
        }
        for (int i = 0; i < n; ++i) {
            ans += dp[i];
        }
        return ans;
    }
};
posted on 2021-12-25 14:36  tziSher  阅读(38)  评论(0编辑  收藏  举报