Maximize cost to empty given array by repetitively removing K array elements | Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Driver code
function maxCostToRemove ( arr , N , K ) { let maxCost = 0 ; arr . sort ( ) ; for ( let i = 0 ; i < N ; i += K ) { maxCost += arr [ i + 1 ] ; } return maxCost ; } let arr = [ 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 ] ; let N = arr . length ; let K = 4 ; document . write ( maxCostToRemove ( arr , N , K ) ) ;