Length of longest sub | Function to find maximum distance between unequal elements ; Calculate maxMean ; Iterate over array and calculate largest subarray with all elements greater or equal to maxMean ; Driver code
function longestSubarray ( arr , n ) { var maxMean = 0 ; for ( var i = 1 ; i < n ; i ++ ) maxMean = Math . max ( maxMean , parseInt ( ( arr [ i ] + arr [ i - 1 ] ) / 2 ) ) ; var ans = 0 ; var subarrayLength = 0 ; for ( var i = 0 ; i < n ; i ++ ) if ( arr [ i ] >= maxMean ) ans = Math . max ( ans , ++ subarrayLength ) ; else subarrayLength = 0 ; return ans ; } var arr = [ 4 , 3 , 3 , 2 , 1 , 4 ] ; var n = arr . length ; document . write ( longestSubarray ( arr , n ) ) ;