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 readonly cost ; Return the cost ; Driver Code ; Given array [ ] arr ; Function Call
using System ; class GFG { static int findCost ( int [ ] a , int n ) { Array . Sort ( a ) ; Array . Reverse ( a ) ; 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 ; } public static void Main ( String [ ] args ) { int [ ] arr = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = arr . Length ; Console . Write ( findCost ( arr , N ) ) ; } }