Count Descending Subarrays
Problem statement
Given an integer array nums, count how many contiguous subarrays of length at least 2 are strictly descending by exactly 1 at every step.
A subarray nums[l..r] is valid if, for every index i with l <= i < r, we have nums[i + 1] = nums[i] - 1.
Function
countDescendingSubarrays(nums: int[]) → long Complete the function countDescendingSubarrays in the editor below.
countDescendingSubarrays has the following parameter:
int[] nums: the input array
Returns long: the number of valid descending subarrays.
Examples
Example 1
nums = [7, 6, 5, 5, 4]return = 4The valid subarrays are [7, 6], [6, 5], [7, 6, 5], and [5, 4].
Example 2
nums = [4, 3, 2, 1]return = 6Every subarray of length at least 2 is valid, so the answer is 3 + 2 + 1 = 6.
Constraints
- The source thread did not provide explicit numeric bounds.
nums.length >= 1- Count only contiguous subarrays whose adjacent values differ by exactly
-1. - Use a wide enough integer type to store the number of valid subarrays.