![]() |
VOOZH | about |
Given an array of integers arr[]. Find the length of the longest subarray such that all the elements of the subarray are smaller than or equal to the length of the subarray.
Example:
Input: arr[] = [1, 2, 3]
Output: 3
Explanation: The longest subarray is the entire array itself [1, 2, 3], which has a length of 3. All elements in the subarray are less than or equal to 3.Input: arr[] = [6, 4, 2, 5]
Output: 0
Explanation: There is no subarray where all elements are less than or equal to the length of the subarray. The longest subarray is empty, which has a length of 0.
Table of Content
The idea is to check every possible subarray, compute its maximum element, and verify if the subarray length is greater than or equal to this maximum. If valid, update the answer with the maximum length found.
3
Intuition
If we are given an array, along with its size and maximum element, we can directly validate whether the array is valid or not (length of array >= maximum element).
What if we treat every element as the maximum element and then try to find the range where that element can actually remain the maximum? So the problem reduces to: For every element arr[i], find the largest window [L..R] where arr[i] is the maximum.
How to find that window?
To find out the window for which an element arr[i] is the maximum:
So, the element arr[i] is the maximum in the subarray that starts just after the greater element on the left and ends just before the greater element on the right (windowLength = (NGE[i] - PGE[i] - 1)).
Check validity
If windowLength >= arr[i], then it forms a valid subarray and keep track of the maximum such length.
3