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
def LongestSubarray ( a , n , k ) : NEW_LINE INDENT pre = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > k ) : NEW_LINE INDENT pre [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT pre [ i ] = - 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + pre [ i ] NEW_LINE DEDENT Len = 0 NEW_LINE lo = 1 NEW_LINE hi = n NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE ok = False NEW_LINE for i in range ( mid - 1 , n ) : NEW_LINE INDENT x = pre [ i ] NEW_LINE if ( i - mid >= 0 ) : NEW_LINE INDENT x -= pre [ i - mid ] NEW_LINE DEDENT if ( x > 0 ) : NEW_LINE INDENT ok = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( ok == True ) : NEW_LINE INDENT Len = mid NEW_LINE lo = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT return Len NEW_LINE DEDENT a = [ 2 , 3 , 4 , 5 , 3 , 7 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( LongestSubarray ( a , n , k ) ) NEW_LINE