Minimum cost of choosing the array element | Function that find the minimum cost of selecting array element ; Sorting the given array in increasing order ; To store the prefix sum of arr [ ] ; Update the pref [ ] to find the cost selecting array element by selecting at most M element ; Prlet the pref [ ] for the result ; Driver Code
function minimumCost ( arr , N , M ) { arr . sort ( ( a , b ) => a - b ) ; let pref = Array . from ( { length : N } , ( _ , i ) => 0 ) ; pref [ 0 ] = arr [ 0 ] ; for ( let i = 1 ; i < N ; i ++ ) { pref [ i ] = arr [ i ] + pref [ i - 1 ] ; } for ( let i = M ; i < N ; i ++ ) { pref [ i ] += pref [ i - M ] ; } for ( let i = 0 ; i < N ; i ++ ) { document . write ( pref [ i ] + " " ) ; } } let arr = [ 6 , 19 , 3 , 4 , 4 , 2 , 6 , 7 , 8 ] ; let M = 2 ; let N = arr . length ; minimumCost ( arr , N , M ) ;