LeetCode 2393: Count Strictly Increasing Subarrays

Problem Description

Explanation

To solve this problem, we can iterate through the array and keep track of the length of the current increasing subarray. Whenever we encounter an element that breaks the increasing sequence, we calculate the number of subarrays that can be formed using the current length of the increasing subarray and add it to the total count. We then reset the length of the current increasing subarray to 1 and continue iterating.

Algorithm:

  1. Initialize a variable count to 0 to keep track of the total count of strictly increasing subarrays.
  2. Initialize a variable length to 1 to keep track of the length of the current increasing subarray.
  3. Iterate through the array starting from index 1:
    • If the current element is greater than the previous element, increment the length of the current increasing subarray.
    • If the current element is not greater than the previous element, calculate the number of subarrays that can be formed using the current length of the increasing subarray and add it to the count.
    • Reset the length of the current increasing subarray to 1.
  4. Return the total count of strictly increasing subarrays.

Time Complexity: O(N) where N is the number of elements in the array.

Space Complexity: O(1)

Solutions

class Solution {
    public int countStrictlyIncreasingSubarrays(int[] nums) {
        int count = 0;
        int length = 1;
        
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i - 1]) {
                length++;
            } else {
                count += length * (length - 1) / 2;
                length = 1;
            }
        }
        
        count += length * (length - 1) / 2;
        
        return count;
    }
}

Loading editor...