Minimum increment operations to make K elements equal | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( vector < int > ar , int k ) { sort ( ar . begin ( ) , ar . end ( ) ) ; int opsNeeded = 0 ; for ( int i = 0 ; i < k ; i ++ ) { opsNeeded += ar [ k - 1 ] - ar [ i ] ; } int ans = opsNeeded ; for ( int i = k ; i < ar . size ( ) ; i ++ ) { opsNeeded = opsNeeded - ( ar [ i - 1 ] - ar [ i - k ] ) ; opsNeeded += ( k - 1 ) * ( ar [ i ] - ar [ i - 1 ] ) ; ans = min ( ans , opsNeeded ) ; } return ans ; } int main ( ) { vector < int > arr = { 3 , 1 , 9 , 100 } ; int n = arr . size ( ) ; int k = 3 ; cout << minOperations ( arr , k ) ; return 0 ; }