Minimum increment operations to make K elements equal | Function to return the minimum number of increment operations required to make any k elements of the array equal ; Sort the array in increasing order ; Calculate the number of operations needed to make 1 st k elements equal to the kth element i . e . the 1 st window ; Answer will be the minimum of all possible k sized windows ; Find the operations needed to make k elements equal to ith element ; Slide the window to the right and subtract increments spent on leftmost element of the previous window ; Add increments needed to make the 1 st k - 1 elements of this window equal to the kth element of the current window ; Driver code
def minOperations ( ar , k ) : NEW_LINE INDENT ar = sorted ( ar ) NEW_LINE opsNeeded = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT opsNeeded += ar [ k - 1 ] - ar [ i ] NEW_LINE DEDENT ans = opsNeeded NEW_LINE for i in range ( k , len ( ar ) ) : NEW_LINE INDENT opsNeeded = opsNeeded - ( ar [ i - 1 ] - ar [ i - k ] ) NEW_LINE opsNeeded += ( k - 1 ) * ( ar [ i ] - ar [ i - 1 ] ) NEW_LINE ans = min ( ans , opsNeeded ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 1 , 9 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minOperations ( arr , k ) ) NEW_LINE