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;
}
};