Maximal Range That Each Element Is Maximum in It
To solve this problem, we can use a monotonic stack.
- Create a stack
stk
to store elements and their positions in descending order. - Initialize two arrays
left
andright
with the same length asnums
, filled with zeros.left[i]
will store the leftmost index where the subarray in whichnums[i]
is maximum starts, andright[i]
will store the rightmost index where it ends. - Loop through the array twice: once from left to right to fill in
right
and once from right to left to fill inleft
. - Calculate the final answer
ans
.
Here’s the code:
|
|
Explanation
- The stack stores elements in descending order. We use this stack to efficiently find the nearest element greater than each
nums[i]
. left[i]
andright[i]
are arrays to store the boundaries of the longest subarray wherenums[i]
is the maximum element.- Finally, we use these boundaries to calculate the length of each subarray.
The time complexity is (O(n)) and the space complexity is (O(n)), which are both acceptable given the constraints.