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


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.

So, if the input is like price = [4, 3, 2, 5] and k = 2, then the output will be Minimum = 5 and Maximum = 9. This is because when k is 2, if we buy one candy and we can take maximum two more for free. In the first case we can buy the candy which costs 2 and take candies worth price 4 and 5 for free, also we can buy candy worth 3 as well, so minimum cost = 2 + 3 = 5. On the other hand, in second case we buy the candy which costs 5 and take candies worth price 2 and 3 for free, or we can also buy candy worth 4 as well. so, max cost = 4 + 5 = 9.

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

Updated on: 20-Aug-2020

732 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements