Cost required to empty a given array by repeated removal of maximum obtained by given operations | C ++ program for the above approach ; Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to the final cost ; Return the cost ; Driver Code ; Given array arr [ ] ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCost ( int * a , int n ) { sort ( a , a + n , greater < int > ( ) ) ; int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int p = a [ j ] - j ; a [ j ] = 0 ; if ( p < 0 ) { p = 0 ; continue ; } count += p ; } return count ; } int main ( ) { int arr [ ] = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findCost ( arr , N ) ; return 0 ; }