Maximize cost to empty given array by repetitively removing K array elements | Java program for the above approach ; 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 ; Drive Code
import java . io . * ; import java . util . Arrays ; class GFG { static int maxCostToRemove ( int arr [ ] , int N , int K ) { int maxCost = 0 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < N ; i += K ) { maxCost += arr [ i + 1 ] ; } return maxCost ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 } ; int N = arr . length ; int K = 4 ; System . out . print ( maxCostToRemove ( arr , N , K ) ) ; } }