# Find the minimum and maximum amount to buy all N candies in Python

PythonServer Side ProgrammingProgramming

Suppose there is a candy store where N different types of candies are available and the prices of all N different types of candies are given. The store also provides an attractive offer. According to this offer, we can buy a single candy from the store and get maximum of K different types of other candies for free. We have to find the minimum amount of money we have to spend to buy all the N different types of candies. We also have to find maximum amount of money we have to spend to buy all the N different types candies. From the both cases we must utilize the offer and obtain maximum possible candies back. If there are k or more candies available, we must select k candies for every candy purchase. But, if less than k candies are available, we must select all candies for a candy purchase.

To solve this, we will follow these steps −

• Define a function get_min() . This will take A,k

• n := size of A

• sort the list A

• res := 0, i:= 0

• while n is non-zero, do

• res := res + A[i]

• n := n-k

• i := i + 1

• return res

• Define a function get_max() . This will take A, k

• n := size of A

• sort the list A

• res := 0, idx := 0

• i:= n-1

• while i>=idx, do

• res := res + A[i]

• idx := idx + k

• i := i - 1

• return res

• From the main method call these two functions to get the results

• get_min(A, k)

• get_max(A, k)

## Example

Let us see the following implementation to get better understanding −

Live Demo

def get_min(A,k):
n = len(A)
A.sort()
res = 0
i=0
while(n):
res += A[i]
n = n-k
i += 1
return res
def get_max(A, k):
n = len(A)
A.sort()
res = 0
idx = 0
i=n-1
while(i>=idx):
res += A[i]
idx += k
i -= 1
return res

A = [4, 3, 2, 5]
k = 2
print(get_min(A, k),get_max(A, k))

## Input

[4, 3, 2, 5], 2

## Output

5 9