2393. Count Strictly Increasing Subarrays

LeetCode 力扣

1. Description

You are given an array nums consisting of positive integers.
Return the number of subarrays of nums that are in strictly increasing order.
A subarray is a contiguous part of an array.

2. Example

Example 1

Input: nums = [1,3,5,4,4,6]
Output: 10
Explanation: The strictly increasing subarrays are the following:

  • Subarrays of length 1: [1], [3], [5], [4], [4], [6].
  • Subarrays of length 2: [1,3], [3,5], [4,6].
  • Subarrays of length 3: [1,3,5].

The total number of subarrays is 6 + 3 + 1 = 10.

Example 2

Input: nums = [1,2,3,4,5]
Output: 15
Explanation: Every subarray is strictly increasing. There are 15 possible subarrays that we can take.

3. Constraints

  • 1 <= nums.length <= 10$^5$
    1 <= nums[i] <= 10$^6$

4. Solutions

Math

n = nums.size()
Time complexity: O(n)
Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
public:
    long long countSubarrays(vector<int> &nums) {
        long long count = 1, length = 1;
        for (int i = 1, n = nums.size(); i < n; ++i) {
            if (nums[i] > nums[i - 1]) {
                ++length;
            } else {
                length = 1;
            }

            count += length;
        }

        return count;
    }
};
comments powered by Disqus