Maximize cost to empty given array by repetitively removing K array elements | C ++ program to implement the above approach ; Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxCostToRemove ( int arr [ ] , int N , int K ) { int maxCost = 0 ; sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i += K ) { maxCost += arr [ i + 1 ] ; } return maxCost ; } int main ( ) { int arr [ ] = { 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 4 ; cout << maxCostToRemove ( arr , N , K ) ; }