Find the minimum and maximum amount to buy all N candies | Function to find the minimum amount to buy all candies ; Buy current candy ; And take k candies for free from the last ; Function to find the maximum amount to buy all candies ; Buy candy with maximum amount ; And get k candies for free from the starting ; Driver code ; Function call
function findMinimum ( arr , n , k ) { let res = 0 ; for ( let i = 0 ; i < n ; i ++ ) { res += arr [ i ] ; n = n - k ; } return res ; } function findMaximum ( arr , n , k ) { let res = 0 , index = 0 ; for ( let i = n - 1 ; i >= index ; i -- ) { res += arr [ i ] ; index += k ; } return res ; } let arr = [ 3 , 2 , 1 , 4 ] ; let n = arr . length ; let k = 2 ; arr . sort ( function ( a , b ) { return a - b ; } ) ; document . write ( findMinimum ( arr , n , k ) + " " + findMaximum ( arr , n , k ) ) ;