Problem
Given an integer array nums
, return the number of non-emptysubarrays with the leftmost element of the subarray not larger than other elements in the subarray.
A subarray is a contiguous part of an array.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 5 * 10^4
0 <= nums[i] <= 10^5
Solution
Method 1 – Monotonic Stack (Next Smaller Element)
Intuition
For each index, find the farthest right index such that all elements in between are at least as large as nums[i]. This can be done efficiently using a monotonic increasing stack.
Approach
- Initialize an empty stack and a variable ans = 0.
- Iterate through the array. For each index, pop from the stack while nums[stack[-1]] > nums[i], and for each pop, add (i - stack[-1]) to ans.
- After the loop, for remaining indices in the stack, add (n - idx) to ans.
- Return ans.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is the length of nums. - 🧺 Space complexity:
O(n)
, for the stack.