Minimize cost to split an array into K subsets such that the cost of each element is its product with its position in the subset | Java program to implement the above approach ; reverses an array ; Function to find the minimum cost to split array into K subsets ; Sort the array in descending order ; Stores minimum cost to split the array into K subsets ; Stores position of elements of a subset ; Iterate over the range [ 1 , N ] ; Calculate the cost to select X - th element of every subset ; Update min_cost ; Update X ; Driver code ; Function call
import java . util . * ; class GFG { static void reverse ( int a [ ] , int n ) { int i , k , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } static int getMinCost ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; reverse ( arr , n ) ; int min_cost = 0 ; int X = 0 ; for ( int i = 0 ; i < n ; i += k ) { for ( int j = i ; j < i + k && j < n ; j ++ ) { min_cost += arr [ j ] * ( X + 1 ) ; } X ++ ; } return min_cost ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 20 , 7 , 8 } ; int K = 2 ; int N = arr . length ; System . out . println ( getMinCost ( arr , N , K ) ) ; } }