Length of longest subarray in which elements greater than K are more than elements not greater than K | Java implementation of above approach ; 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
class GFG { static int LongestSubarray ( int a [ ] , int n , int k ) { int [ ] pre = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] > k ) pre [ i ] = 1 ; else pre [ i ] = - 1 ; } for ( int i = 1 ; i < n ; i ++ ) pre [ i ] = pre [ i - 1 ] + pre [ i ] ; int len = 0 ; int lo = 1 , hi = n ; while ( lo <= hi ) { int mid = ( lo + hi ) / 2 ; boolean ok = false ; for ( int i = mid - 1 ; i < n ; i ++ ) { int 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 ; } public static void main ( String [ ] args ) { int a [ ] = { 2 , 3 , 4 , 5 , 3 , 7 } ; int k = 3 ; int n = a . length ; System . out . println ( LongestSubarray ( a , n , k ) ) ; } }