1063. Number of Valid Subarrays π
Description
Given an integer array nums, return the number of non-empty subarrays with the leftmost element of the subarray not larger than other elements in the subarray.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [1,4,2,5,3] Output: 11 Explanation: There are 11 valid subarrays: [1],[4],[2],[5],[3],[1,4],[2,5],[1,4,2],[2,5,3],[1,4,2,5],[1,4,2,5,3].
Example 2:
Input: nums = [3,2,1] Output: 3 Explanation: The 3 valid subarrays are: [3],[2],[1].
Example 3:
Input: nums = [2,2,2] Output: 6 Explanation: There are 6 valid subarrays: [2],[2],[2],[2,2],[2,2],[2,2,2].
Constraints:
1 <= nums.length <= 5 * 1040 <= nums[i] <= 105
Solutions
Solution 1
Thinking
A subarray is valid iff its left end is the minimum. For each \(i\) the right end may extend up to the next strictly smaller value. \(n\le 5\times 10^4\) needs a linear next-smaller scan.
A decreasing index stack from the right pops every top that is not smaller than \(nums[i]\); the new top (or \(n\)) is the boundary and contributes that index minus \(i\).
Storing \(\textit{right}[i]\) and summing matches the definition.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
Solution 2
Thinking
Solution 1 stores the whole \(\textit{right}\) array. The boundary is known immediately while scanning backward.
The same stack adds \((stk[-1]\text{ or }n)-i\) to the answer on the fly.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |