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 | 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
function reverse ( a , n ) { var i , k , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } function getMinCost ( arr , n , k ) { arr . sort ( ( a , b ) => b - a ) ; var min_cost = 0 ; var X = 0 ; for ( var i = 0 ; i < n ; i += k ) { for ( var j = i ; j < i + k && j < n ; j ++ ) { min_cost += arr [ j ] * ( X + 1 ) ; } X ++ ; } return min_cost ; } var arr = [ 9 , 20 , 7 , 8 ] ; var K = 2 ; var N = arr . length ; document . write ( getMinCost ( arr , N , K ) ) ;