Leetcode

Number of Smooth Descent Periods of a Stock

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  long long getDescentPeriods(vector<int>& prices) {
    long long ans = 1;  // prices[0]
    int dp = 1;

    for (int i = 1; i < prices.size(); ++i) {
      if (prices[i] == prices[i - 1] - 1) {
        ++dp;
      } else {
        dp = 1;
      }
      ans += dp;
    }

    return ans;
  }
};

JAVA

class Solution {
  public long getDescentPeriods(int[] prices) {
    long ans = 1; // prices[0]
    int dp = 1;

    for (int i = 1; i < prices.size(); ++i) {
      if (prices[i] == prices[i - 1] - 1) {
        ++dp;
      } else {
        dp = 1;
      }
      ans += dp;
    }

    return ans;
  }
}

Python

class Solution:
  def getDescentPeriods(self, prices: List[int]) -> int:
    ans = 1  # prices[0]
    dp = 1

    for i in range(1, len(prices)):
      if prices[i] == prices[i - 1] - 1:
        dp += 1
      else:
        dp = 1
      ans += dp

    return ans