Back to course home
0% completed
Vote For New Content
Have better solution
gajendra.naidu.t
Dec 24, 2024
There is a solution with linear complexity using Queues.
public int maxSubarrayLength(int[] nums) { int n = nums.length; Deque<Integer> stack = new ArrayDeque<>(); for (int i = n - 1; i >= 0; i--) { if (stack.isEmpty() || nums[i] < nums[stack.peek()]) { stack.push(i); } } int ans = 0; int m = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { while (!stack.isEmpty() && stack.peek() <= i) { stack.pop(); } if (nums[i] > m) { m = nums[i]; while (!stack.isEmpty() && m > nums[stack.peek()]) { ans = Math.max(ans, stack.pop() - i + 1); } } } return ans; }
0
0
Comments
Comments
On this page