Cost required to empty a given array by repeated removal of maximum obtained by given operations | Java 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
import java . util . * ; class GFG { static int findCost ( Integer [ ] a , int n ) { Arrays . sort ( a , Collections . reverseOrder ( ) ) ; 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 ) { Integer arr [ ] = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = arr . length ; System . out . print ( findCost ( arr , N ) ) ; } }