Cost required to empty a given array by repeated removal of maximum obtained by given operations | 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 ; Given array arr [ ] ; Function Call
function findCost ( a , n ) { a . sort ( ( x , y ) => y - x ) ; var count = 0 ; for ( var j = 0 ; j < n ; j ++ ) { var p = a [ j ] - j ; a [ j ] = 0 ; if ( p < 0 ) { p = 0 ; continue ; } count += p ; } return count ; } var arr = [ 1 , 6 , 7 , 4 , 2 , 5 , 3 ] ; var N = arr . length ; document . write ( findCost ( arr , N ) ) ;