Input: nums =[1,5,4,3,6]Output: [1,4,2,1,5]Explanation: For nums[0] the longest subarray in which 1is the maximum is nums[0..0] so ans[0]=1.For nums[1] the longest subarray in which 5is the maximum is nums[0..3] so ans[1]=4.For nums[2] the longest subarray in which 4is the maximum is nums[2..3] so ans[2]=2.For nums[3] the longest subarray in which 3is the maximum is nums[3..3] so ans[3]=1.For nums[4] the longest subarray in which 6is the maximum is nums[0..4] so ans[4]=5.
Example 2:
1
2
3
Input: nums =[1,2,3,4,5]Output: [1,2,3,4,5]Explanation: For nums[i] the longest subarray in which it's the maximum is nums[0..i] so ans[i]= i +1.
For each element, the maximal subarray where it is the maximum is bounded by the first greater element to the left and right. Using a monotonic stack, we can efficiently find these bounds for all elements.
classSolution {
publicint[]maximumLength(int[] nums) {
int n = nums.length;
int[] prev =newint[n], next =newint[n], ans =newint[n];
Arrays.fill(prev, -1);
Arrays.fill(next, n);
Deque<Integer> st =new ArrayDeque<>();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && nums[st.peek()]< nums[i]) st.pop();
if (!st.isEmpty()) prev[i]= st.peek();
st.push(i);
}
st.clear();
for (int i = n-1; i >= 0; i--) {
while (!st.isEmpty() && nums[st.peek()]< nums[i]) st.pop();
if (!st.isEmpty()) next[i]= st.peek();
st.push(i);
}
for (int i = 0; i < n; i++) {
ans[i]= next[i]- prev[i]- 1;
}
return ans;
}
}
classSolution {
funmaximumLength(nums: IntArray): IntArray {
val n = nums.size
val prev = IntArray(n) { -1 }
val next = IntArray(n) { n }
val ans = IntArray(n)
val st = ArrayDeque<Int>()
for (i in0 until n) {
while (st.isNotEmpty() && nums[st.last()] < nums[i]) st.removeLast()
if (st.isNotEmpty()) prev[i] = st.last()
st.addLast(i)
}
st.clear()
for (i in n-1 downTo 0) {
while (st.isNotEmpty() && nums[st.last()] < nums[i]) st.removeLast()
if (st.isNotEmpty()) next[i] = st.last()
st.addLast(i)
}
for (i in0 until n) {
ans[i] = next[i] - prev[i] - 1 }
return ans
}
}
classSolution:
defmaximumLength(self, nums: list[int]) -> list[int]:
n = len(nums)
prev = [-1] * n
next_ = [n] * n
st = []
for i in range(n):
while st and nums[st[-1]] < nums[i]:
st.pop()
if st:
prev[i] = st[-1]
st.append(i)
st.clear()
for i in range(n-1, -1, -1):
while st and nums[st[-1]] < nums[i]:
st.pop()
if st:
next_[i] = st[-1]
st.append(i)
return [next_[i] - prev[i] -1for i in range(n)]