LeetCode Entry
2110. Number of Smooth Descent Periods of a Stock
Decreasing subarrays
2110. Number of Smooth Descent Periods of a Stock medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1205
Problem TLDR
Decreasing subarrays #medium
Intuition
Just count them like and arithmetic progression.
Approach
- res += count++
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
// 40ms
fun getDescentPeriods(p: IntArray) =
p.indices.fold(0 to 0L) { (cnt, res), i ->
val c = 1 + if (i > 0 && p[i] == p[i-1] - 1) cnt else 0
c to (res + c)
}.second
// 0ms
pub fn get_descent_periods(p: Vec<i32>) -> i64 {
(0..p.len()).fold((0,0), |(cnt,res), i| {
let c = 1 + if i > 0 && p[i] == p[i-1]-1 { cnt } else { 0 };
(c, res + c)
}).1
}