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 exactly1. The first day of the period is exempted from this rule.
Input: prices =[3,2,1,4]Output: 7Explanation: 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.
Input: prices =[8,6,7,7]Output: 4Explanation: 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.
Every single day is a smooth descent period. For longer periods, if the current price is exactly 1 less than the previous, we can extend the previous descent period. We keep track of the length of the current descent and sum up all such periods.
classSolution {
public:longlong getDescentPeriods(vector<int>& prices) {
longlong ans =1, cur =1;
for (int i =1; i < prices.size(); ++i) {
if (prices[i] == prices[i-1] -1) ++cur;
else cur =1;
ans += cur;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcgetDescentPeriods(prices []int) int64 {
ans, cur:= int64(1), int64(1)
fori:=1; i < len(prices); i++ {
ifprices[i] ==prices[i-1]-1 {
cur++ } else {
cur = 1 }
ans+=cur }
returnans}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
publiclonggetDescentPeriods(int[] prices) {
long ans = 1, cur = 1;
for (int i = 1; i < prices.length; ++i) {
if (prices[i]== prices[i-1]- 1) ++cur;
else cur = 1;
ans += cur;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
fungetDescentPeriods(prices: IntArray): Long {
var ans = 1Lvar cur = 1Lfor (i in1 until prices.size) {
if (prices[i] == prices[i-1] - 1) cur++else cur = 1L ans += cur
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defgetDescentPeriods(self, prices: list[int]) -> int:
ans = cur =1for i in range(1, len(prices)):
if prices[i] == prices[i-1] -1:
cur +=1else:
cur =1 ans += cur
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnget_descent_periods(prices: Vec<i32>) -> i64 {
letmut ans =1i64;
letmut cur =1i64;
for i in1..prices.len() {
if prices[i] == prices[i-1] -1 {
cur +=1;
} else {
cur =1;
}
ans += cur;
}
ans
}
}