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
using System ; class GFG { static void minimumCost ( int [ ] arr , int N , int M ) { Array . Sort ( arr ) ; int [ ] pref = new int [ 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 ++ ) { Console . Write ( pref [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 6 , 19 , 3 , 4 , 4 , 2 , 6 , 7 , 8 } ; int M = 2 ; int N = arr . Length ; minimumCost ( arr , N , M ) ; } }