Longest Subarray with first element greater than or equal to Last element | Search function for searching the first element of the subarray which is greater or equal to the last element ( num ) ; Returns length of the longest array with first element smaller than the last element . ; Search space for the potential first elements . ; It will store the Indexes of the elements of search space in the original array . ; Initially the search space is empty . ; We will add an ith element in the search space if the search space is empty or if the ith element is greater than the last element of the search space . ; We will search for the index first element in the search space and we will use it find the index of it in the original array . ; Update the answer if the length of the subarray is greater than the previously calculated lengths . ; Driver code
function binarySearch ( searchSpace , s , e , num ) { let ans = 0 ; while ( s <= e ) { let mid = Math . floor ( ( s + e ) / 2 ) ; if ( searchSpace [ mid ] >= num ) { ans = mid ; e = mid - 1 ; } else s = mid + 1 ; } return ans ; } function longestSubArr ( arr , n ) { let searchSpace = new Array ( n ) ; let index = new Array ( n ) ; let j = 0 ; let ans = 0 ; for ( let i = 0 ; i < n ; ++ i ) { if ( j == 0 searchSpace [ j - 1 ] < arr [ i ] ) { searchSpace [ j ] = arr [ i ] ; index [ j ] = i ; j ++ ; } let idx = binarySearch ( searchSpace , 0 , j - 1 , arr [ i ] ) ; ans = Math . max ( ans , i - index [ idx ] + 1 ) ; } return ans ; } let arr = [ - 5 , - 1 , 7 , 5 , 1 , - 2 ] ; let n = arr . length ; document . write ( longestSubArr ( arr , n ) ) ;