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
< ? php function findMinimum ( $ arr , $ n , $ k ) { $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ res += $ arr [ $ i ] ; $ n = $ n - $ k ; } return $ res ; } function findMaximum ( $ arr , $ n , $ k ) { $ res = 0 ; $ index = 0 ; for ( $ i = $ n - 1 ; $ i >= $ index ; $ i -- ) { $ res += $ arr [ $ i ] ; $ index += $ k ; } return $ res ; } $ arr = array ( 3 , 2 , 1 , 4 ) ; $ n = sizeof ( $ arr ) ; $ k = 2 ; sort ( $ arr ) ; sort ( $ arr , $ n ) ; echo findMinimum ( $ arr , $ n , $ k ) , " " , findMaximum ( $ arr , $ n , $ k ) ; return 0 ; ? >