Number of Smooth Descent Periods of a Stock

medium sliding window array run length

Problem

Given an integer array prices where prices[i] is the stock price on day i, a smooth descent period is one or more contiguous days where each day's price is exactly 1 lower than the previous day (the first day is exempt). Return the total number of smooth descent periods.

Inputprices = [3,2,1,4]
Output7
The periods are [3], [2], [1], [4], [3,2], [2,1], [3,2,1]. Each single day counts, plus every longer run that descends by 1.
Inputprices = [8,6,7,7]
Output4
Only the 4 single days qualify; [8,6] fails because 8 − 6 ≠ 1.

def get_descent_periods(prices):
    total = 0
    cur = 0
    for i in range(len(prices)):
        if i > 0 and prices[i] == prices[i - 1] - 1:
            cur += 1
        else:
            cur = 1
        total += cur
    return total
function getDescentPeriods(prices) {
  let total = 0;
  let cur = 0;
  for (let i = 0; i < prices.length; i++) {
    if (i > 0 && prices[i] === prices[i - 1] - 1) {
      cur += 1;
    } else {
      cur = 1;
    }
    total += cur;
  }
  return total;
}
long getDescentPeriods(int[] prices) {
    long total = 0;
    long cur = 0;
    for (int i = 0; i < prices.length; i++) {
        if (i > 0 && prices[i] == prices[i - 1] - 1) {
            cur += 1;
        } else {
            cur = 1;
        }
        total += cur;
    }
    return total;
}
long long getDescentPeriods(vector<int>& prices) {
    long long total = 0;
    long long cur = 0;
    for (int i = 0; i < (int)prices.size(); i++) {
        if (i > 0 && prices[i] == prices[i - 1] - 1) {
            cur += 1;
        } else {
            cur = 1;
        }
        total += cur;
    }
    return total;
}
Time: O(n) Space: O(1)