Gauss' 10y-old formula at work - Part II

In order to count the number of contiguous subarrays meeting the below constraints, we make use one more time of the famous Gauss summation formula when the dude was 10y old. Linear time. Code is below, cheers, ACC.

Count Strictly Increasing Subarrays - LeetCode

2393. Count Strictly Increasing Subarrays
Medium

You are given an array nums consisting of positive integers.

Return the number of subarrays of nums that are in strictly increasing order.

subarray is a contiguous part of an array.

 

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.

public long CountSubarrays(int[] nums)
{
    int leftIndex = 0;
    int rightIndex = 1;

    long retVal = 0;
    while (rightIndex < nums.Length)
    {
        if (nums[rightIndex] <= nums[rightIndex - 1])
        {
            long len = rightIndex - leftIndex;
            retVal += (len * (len + 1)) / 2;
            leftIndex = rightIndex;
        }
        rightIndex++;
    }

    if (nums.Length > 1 && nums[nums.Length - 1] > nums[nums.Length - 2])
    {
        long len = rightIndex - leftIndex;
        retVal += (len * (len + 1)) / 2;
    }
    else
    {
        retVal++;
    }

    return retVal;
}

Comments

Popular posts from this blog

Changing the root of a binary tree

ProjectEuler Problem 719 (some hints, but no spoilers)

The Power Sum, a recursive problem by HackerRank