Length of longest subarray in which elements greater than K are more than elements not greater than K | Function to find the length of a longest subarray in which elements greater than K are more than elements not greater than K ; Create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; Taking prefix sum over it ; len will store maximum length of subarray ; This indicate there is at least one subarray of length mid that has sum > 0 ; Check every subarray of length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of length mid ; Satisfy our given condition ; Check for higher length as we get length mid ; Check for lower length as we did not get length mid ; Driver code
function LongestSubarray ( a , n , k ) { var pre = Array . from ( { length : n } , ( _ , i ) => 0 ) ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] > k ) pre [ i ] = 1 ; else pre [ i ] = - 1 ; } for ( i = 1 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + pre [ i ] ; var len = 0 ; var lo = 1 , hi = n ; while ( lo <= hi ) { var mid = parseInt ( ( lo + hi ) / 2 ) ; var ok = false ; for ( i = mid - 1 ; i < n ; i ++ ) { var x = pre [ i ] ; if ( i - mid >= 0 ) x -= pre [ i - mid ] ; if ( x > 0 ) { ok = true ; break ; } } if ( ok == true ) { len = mid ; lo = mid + 1 ; } else hi = mid - 1 ; } return len ; } var a = [ 2 , 3 , 4 , 5 , 3 , 7 ] ; var k = 3 ; var n = a . length ; document . write ( LongestSubarray ( a , n , k ) ) ;