• Algorithm线性dpleetcode2110. 股票平滑下跌阶段的数目







    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;
        }
    };
    
  • 相关阅读:
    C++ 与 C 的预处理能力
    unicore32linuxgcc 预定义宏
    内核中的原子上下文
    ConText
    PREEMPT_ACTIVE
    对象和类
    java的getClass()函数
    堆栈以及对象的引用
    public、protected、default、private作用域
    android 环境变量搭建
  • 原文地址:https://www.cnblogs.com/t1314/p/15730477.html
Copyright © 2020-2023  润新知