Maximize length of subarray having equal elements by adding at most K | Function to find the maximum number of indices having equal elements after adding at most k numbers ; Sort the array in ascending order ; Make prefix sum array ; Initialize variables ; Update mid ; Check if any subarray can be obtained of length mid having equal elements ; Decrease max to mid ; Function to check if a subarray of length len consisting of equal elements can be obtained or not ; Sliding window ; Last element of the sliding window will be having the max size in the current window ; The current number of element in all indices of the current sliding window ; If the current number of the window , added to k exceeds totalNumbers ; Driver Code ; Function call
function maxEqualIdx ( arr , k ) { arr . sort ( ) ; let prefixSum = new Array ( arr . length + 1 ) . fill ( 0 ) ; prefixSum [ 1 ] = arr [ 0 ] ; for ( let i = 1 ; i < prefixSum . length - 1 ; ++ i ) { prefixSum [ i + 1 ] = prefixSum [ i ] + arr [ i ] ; } let max = arr . length ; let min = 1 ; let ans = 1 ; while ( min <= max ) { let mid = Math . floor ( ( max + min ) / 2 ) ; if ( check ( prefixSum , mid , k , arr ) ) { ans = mid ; min = mid + 1 ; } else { max = mid - 1 ; } } return ans ; } function check ( pSum , len , k , a ) { let i = 0 ; let j = len ; while ( j <= a . length ) { let maxSize = a [ j - 1 ] ; let totalNumbers = maxSize * len ; let currNumbers = pSum [ j ] - pSum [ i ] ; if ( currNumbers + k >= totalNumbers ) { return true ; } else { i ++ ; j ++ ; } } return false ; } let arr = [ 1 , 1 , 1 ] ; let k = 7 ; document . write ( maxEqualIdx ( arr , k ) ) ;