Maximum elements that can be made equal with k updates | Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; It can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum So difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; Initializing the prefix array and maximum array ; Calculating prefix sum of the array ; Calculating max value upto that position in the array ; Binary search applied for computation here ; printing result ; Driver code
< ? php function ElementsCalculationFunc ( $ pre , $ maxx , $ x , $ k , $ n ) { for ( $ i = 0 , $ j = $ x ; $ j <= $ n ; $ j ++ , $ i ++ ) { if ( $ x * $ maxx [ $ j ] - ( $ pre [ $ j ] - $ pre [ $ i ] ) <= $ k ) return true ; } return false ; } function MaxNumberOfElements ( $ a , $ n , $ k ) { sort ( $ a ) ; for ( $ i = 0 ; $ i <= $ n ; ++ $ i ) { $ pre [ $ i ] = 0 ; $ maxx [ $ i ] = 0 ; } for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { $ pre [ $ i ] = $ pre [ $ i - 1 ] + $ a [ $ i - 1 ] ; $ maxx [ $ i ] = max ( $ maxx [ $ i - 1 ] , $ a [ $ i - 1 ] ) ; } $ l = 1 ; $ r = $ n ; $ ans ; while ( $ l < $ r ) { $ mid = ( $ l + $ r ) / 2 ; if ( ElementsCalculationFunc ( $ pre , $ maxx , $ mid - 1 , $ k , $ n ) ) { $ ans = $ mid ; $ l = $ mid + 1 ; } else $ r = $ mid - 1 ; } echo $ ans , " STRNEWLINE " ; } $ arr = array ( 2 , 4 , 9 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; $ k = 3 ; MaxNumberOfElements ( $ arr , $ n , $ k ) ; #This  code is contributed by akt_mit. NEW_LINE ? >