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
def findCost ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT p = a [ j ] - j NEW_LINE a [ j ] = 0 NEW_LINE if ( p < 0 ) : NEW_LINE INDENT p = 0 NEW_LINE continue NEW_LINE DEDENT count += p NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 , 6 , 7 , 4 , 2 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findCost ( arr , N ) ) NEW_LINE