Minimum cost of choosing the array element | C ++ program for the above approach ; 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 ; Print the pref [ ] for the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumCost ( int arr [ ] , int N , int M ) { sort ( arr , arr + N ) ; int pref [ N ] ; pref [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < N ; i ++ ) { pref [ i ] = arr [ i ] + pref [ i - 1 ] ; } for ( int i = M ; i < N ; i ++ ) { pref [ i ] += pref [ i - M ] ; } for ( int i = 0 ; i < N ; i ++ ) { cout << pref [ i ] << ' ▁ ' ; } } int main ( ) { int arr [ ] = { 6 , 19 , 3 , 4 , 4 , 2 , 6 , 7 , 8 } ; int M = 2 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; minimumCost ( arr , N , M ) ; return 0 ; }