The brute force writes itself in like two minutes, which is exactly why it's a trap you can't fall into.
Clarify the problem definition and edge cases, then propose an O(n) solution using a monotonic stack to find the nearest greater elements to the left and right for each element. Explain how to use these boundaries to compute the longest valid subarray where the endpoints are strictly greater than all interior elements.
Pro tip: Emphasize that the endpoints must be strictly greater than every element in between, so the subarray length is determined by the distance between the nearest greater elements on both sides. Mention that handling duplicates correctly is crucial and can be done by using strict comparisons in the stack.
Restate the problem to ensure understanding: find the maximum length of a contiguous subarray where the first and last elements are both strictly greater than all elements in between. Discuss edge cases such as arrays of length 0, 1, 2, and arrays with all equal elements.
Note that for any valid subarray, the endpoints are the nearest greater elements to each other within that subarray. Thus, the problem reduces to finding, for each element, the nearest greater element to its left and right, and then computing the maximum distance between such pairs.
Use a monotonic decreasing stack to find the nearest greater element to the left for each index, and similarly to the right. Then, for each element, consider it as the left endpoint and find the farthest right endpoint that is greater than all elements in between, which is essentially the nearest greater element to the right that is also greater than the left endpoint.
Iterate through the array and for each index i, if there is a nearest greater element to the right at index j, and all elements between i and j are less than both arr[i] and arr[j], then the length j-i+1 is a candidate. However, to ensure the condition, we need to check that the maximum element between i and j is less than min(arr[i], arr[j]). This can be done by precomputing range maximum queries or by using the stack to directly find valid pairs.
The monotonic stack approach runs in O(n) time and O(n) space. Explain that this meets the requirement of avoiding O(n²) solutions.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.