In a candy store, there are N different types of candies available and the prices of all the N different types of candies are provided. There is also an attractive offer by the candy store. We can buy a single candy from the store and get at most K other candies (all are different types) for free.
- Find the minimum amount of money we have to spend to buy all the N different candies.
- Find the maximum amount of money we have to spend to buy all the N different candies.
In both cases, we must utilize the offer and get the maximum possible candies back. If k or more candies are available, we must take k candies for every candy purchase. If less than k candies are available, we must take all candies for a candy purchase.
Examples:Â
Input :  
price[] = {3, 2, 1, 4}
k = 2
Output :  
Min = 3, Max = 7
Explanation :
Since k is 2, if we buy one candy we can take 
atmost two more for free.
So in the first case we buy the candy which 
costs 1 and take candies worth 3 and 4 for 
free, also you buy candy worth 2 as well.
So min cost = 1 + 2 = 3.
In the second case we buy the candy which 
costs 4 and take candies worth 1 and 2 for 
free, also We buy candy worth 3 as well.
So max cost = 3 + 4 = 7.
One important thing to note is, we must use the offer and get maximum candies back for every candy purchase. So if we want to minimize the money, we must buy candies at minimum cost and get candies of maximum costs for free. To maximize the money, we must do the reverse. Below is an algorithm based on this.
First Sort the price array. For finding minimum amount : Start purchasing candies from starting and reduce k free candies from last with every single purchase. For finding maximum amount : Start purchasing candies from the end and reduce k free candies from starting in every single purchase.
Below image is an illustration of the above approach:
Minimum amount :Â
Maximum amount :Â
Below is the implementation of the above approach:Â
C++
| // C++ implementation to find the minimum // and maximum amount #include <bits/stdc++.h> usingnamespacestd;  Â// Function to find the minimum amount // to buy all candies intfindMinimum(intarr[], intn, intk) {     intres = 0;     for(inti = 0; i < n; i++) {         // Buy current candy         res += arr[i];  Â        // And take k candies for free         // from the last         n = n - k;     }     returnres; }  Â// Function to find the maximum amount // to buy all candies intfindMaximum(intarr[], intn, intk) {     intres = 0, index = 0;  Â    for(inti = n - 1; i >= index; i--)      {         // Buy candy with maximum amount         res += arr[i];  Â        // And get k candies for free from         // the starting         index += k;     }     returnres; }  Â// Driver code intmain() {     intarr[] = { 3, 2, 1, 4 };     intn = sizeof(arr) / sizeof(arr[0]);     intk = 2;     sort(arr, arr + n);  Â    // Function call     cout << findMinimum(arr, n, k) << " "         << findMaximum(arr, n, k) << endl;     return0; } | 
Java
| // Java implementation to find the // minimum and maximum amount importjava.util.*;  ÂclassGFG {  Â    // Function to find the minimum     // amount to buy all candies     staticintfindMinimum(intarr[], intn, intk)     {         intres = 0;         for(inti = 0; i < n; i++) {             // Buy current candy             res += arr[i];  Â            // And take k candies for free             // from the last             n = n - k;         }         returnres;     }  Â    // Function to find the maximum     // amount to buy all candies     staticintfindMaximum(intarr[], intn, intk)     {         intres = 0, index = 0;  Â        for(inti = n - 1; i >= index; i--)          {             // Buy candy with maximum amount             res += arr[i];  Â            // And get k candies for free from             // the starting             index += k;         }         returnres;     }  Â    // Driver code     publicstaticvoidmain(String[] args)     {         intarr[] = { 3, 2, 1, 4};         intn = arr.length;         intk = 2;         Arrays.sort(arr);  Â        // Function call         System.out.println(findMinimum(arr, n, k) + " "                           + findMaximum(arr, n, k));     } }  Â// This code is contributed by prerna saini | 
Python3
| # Python implementation # to find the minimum # and maximum amount  Â# Function to find # the minimum amount # to buy all candies  Â ÂdeffindMinimum(arr, n, k):  Â    res =0    i =0    while(i<n):  Â        # Buy current candy         res +=arr[i]  Â        # And take k         # candies for free         # from the last         n =n-k         i +=1    returnres  Â# Function to find # the maximum amount # to buy all candies  Â ÂdeffindMaximum(arr, n, k):  Â    res =0    index =0    i =n-1    while(i >=index):  Â        # Buy candy with         # maximum amount         res +=arr[i]  Â        # And get k candies         # for free from         # the starting         index +=k         i -=1 Â    returnres  Â# Driver code arr =[1,2,3,4,5,6,7,8,9,10] n =len(arr) k =0 Âarr.sort()  Â# Function call print(findMinimum(arr, n, k), " ",       findMaximum(arr, n, k))  Â# This code is contributed # by Anant Agarwal.  | 
C#
| // C# implementation to find the // minimum and maximum amount usingSystem;  ÂpublicclassGFG {  Â    // Function to find the minimum     // amount to buy all candies     staticintfindMinimum(int[] arr, intn, intk)     {         intres = 0;         for(inti = 0; i < n; i++)          {  Â            // Buy current candy             res += arr[i];  Â            // And take k candies for             // free from the last             n = n - k;         }  Â        returnres;     }  Â    // Function to find the maximum     // amount to buy all candies     staticintfindMaximum(int[] arr, intn, intk)     {         intres = 0, index = 0;  Â        for(inti = n - 1; i >= index; i--)          {             // Buy candy with maximum             // amount             res += arr[i];  Â            // And get k candies for free             // from the starting             index += k;         }  Â        returnres;     }  Â    // Driver code     publicstaticvoidMain()     {         int[] arr = { 3, 2, 1, 4 };         intn = arr.Length;         intk = 2;         Array.Sort(arr);  Â        // Function call         Console.WriteLine(findMinimum(arr, n, k) + " "                          + findMaximum(arr, n, k));     } }  Â// This code is contributed by Sam007. | 
PHP
| <?php // PHP implementation to find the minimum // and maximum amount  Â// Function to find the minimum amount // to buy all candies functionfindMinimum($arr, $n,$k) {     $res= 0;     for($i= 0; $i< $n; $i++)     {          Â        // Buy current candy         $res+= $arr[$i];  Â        // And take k candies for free         // from the last         $n= $n- $k;     }     return$res; }  Â// Function to find the maximum amount // to buy all candies functionfindMaximum($arr, $n, $k) {     $res= 0;      $index= 0;  Â    for($i= $n- 1; $i>= $index; $i--)     {          Â        // Buy candy with maximum amount         $res+= $arr[$i];  Â        // And get k candies         // for free from         // the starting         $index+= $k;     }     return$res; }  Â    // Driver Code     $arr= array(3, 2, 1, 4);     $n= sizeof($arr);     $k= 2;     sort($arr); sort($arr,$n);  Â    // Function call     echofindMinimum($arr, $n, $k)," "            ,findMaximum($arr, $n, $k);     return0;  Â// This code is contributed by nitin mittal. ?>  | 
Javascript
| <script>  Â// Javascript implementation to find the // minimum and maximum amount      Â// Function to find the minimum // amount to buy all candies functionfindMinimum(arr,n,k) {     let res = 0;      Â    for(let i = 0; i < n; i++)     {          Â        // Buy current candy         res += arr[i];  Â        // And take k candies for free         // from the last         n = n - k;     }     returnres; }  Â// Function to find the maximum // amount to buy all candies functionfindMaximum(arr,n,k) {     let res = 0, index = 0;  Â    for(let i = n - 1; i >= index; i--)     {          Â        // Buy candy with maximum amount         res += arr[i];  Â        // And get k candies for free from         // the starting         index += k;     }     returnres; }  Â// Driver code let arr = [ 3, 2, 1, 4 ]; let  n = arr.length; let  k = 2; arr.sort(function(a, b){returna - b;});  Â// Function call document.write(findMinimum(arr, n, k) + " "+                 findMaximum(arr, n, k));  Â// This code is contributed by patel2127  Â</script> | 
3 7
Time Complexity : O(nlogn) 
Auxiliary Space: O(1)
Another Implementation:
We can use the help of The Least integer function (Ceiling function) using built-in ceil() function to implement:
Below is the implementation in Python:
C++
| // C++ implementation // to find the minimum // and maximum amount #include <bits/stdc++.h> usingnamespacestd;  Â// function to find the maximum // and the minimum cost required voidfind(vector<int> arr, intn, intk) {  Â    // Sort the array     sort(arr.begin(), arr.end());     intb = ceil(n / k * 1.0);     intmin_sum = 0, max_sum = 0;  Â    for(inti = 0; i < b; i++)        min_sum += arr[i];     for(inti = 2; i < arr.size(); i++)       max_sum += arr[i];  Â    // print the minimum cost     cout << "minimum "<< min_sum << endl;  Â    // print the maximum cost     cout << "maximum "<< max_sum << endl;  Â}  Â Â// Driver code intmain() {   vector<int> arr = {3, 2, 1, 4};   intn = arr.size();   intk = 2;  Â  // Function call   find(arr,n,k); }  Â// This code is contributed by mohit kumar 29.  | 
Java
| // Java implementation to find the minimum // and maximum amount importjava.io.*; importjava.util.Arrays; importjava.lang.Math;  ÂclassGFG{  Â// Function to find the maximum // and the minimum cost required staticvoidfind(int[] arr, intn, intk) {      Â    // Sort the array     Arrays.sort(arr);     intb = (int)Math.ceil(n / k * 1.0);     intmin_sum = 0, max_sum = 0;  Â    for(inti = 0; i < b; i++)         min_sum += arr[i];     for(inti = 2; i < arr.length; i++)         max_sum += arr[i];  Â    // Print the minimum cost     System.out.println("minimum "+ min_sum);  Â    // Print the maximum cost     System.out.println("maximum "+ max_sum); }  Â// Driver code publicstaticvoidmain (String[] args) {     int[] arr = { 3, 2, 1, 4};     intn = arr.length;     intk = 2;  Â    // Function call     find(arr, n, k); } }  Â// This code is contributed by shivanisinghss2110 | 
Python3
| # Python implementation # to find the minimum # and maximum amount  Â#import ceil function frommath importceil  Â# function to find the maximum # and the minimum cost required deffind(arr,n,k):       Â    # Sort the array     arr.sort()     b =int(ceil(n/k))      Â    # print the minimum cost     print("minimum ",sum(arr[:b]))      Â    # print the maximum cost     print("maximum ", sum(arr[-b:]))      Â     Â# Driver Code arr =[3, 2, 1, 4] n =len(arr) k =2 Â# Function call find(arr,n,k) | 
C#
| // C# implementation to find the minimum // and maximum amount usingSystem;  ÂclassGFG{  Â// Function to find the maximum // and the minimum cost required staticvoidfind(int[] arr, intn, intk) {      Â    // Sort the array     Array.Sort(arr);     intb = (int)Math.Ceiling(n / k * 1.0);     intmin_sum = 0, max_sum = 0;  Â    for(inti = 0; i < b; i++)         min_sum += arr[i];     for(inti = 2; i < arr.Length; i++)         max_sum += arr[i];  Â    // Print the minimum cost     Console.WriteLine("minimum "+ min_sum);  Â    // Print the maximum cost     Console.WriteLine("maximum "+ max_sum); }  Â// Driver code publicstaticvoidMain() {     int[] arr = { 3, 2, 1, 4 };     intn = arr.Length;     intk = 2;  Â    // Function call     find(arr, n, k); } }  Â// This code is contributed by ukasp | 
Javascript
| <script>  Â// JavaScript implementation // to find the minimum // and maximum amount      Â    // function to find the maximum // and the minimum cost required     functionfind(arr,n,k)     {         // Sort the array     arr.sort(function(a,b){returna-b;});     let b = Math.floor(Math.ceil(n/k));      Â    let min_sum = 0, max_sum = 0;   Â    for(let i = 0; i < b; i++)       min_sum += arr[i];     for(let i = 2; i < arr.length; i++)       max_sum += arr[i];       Â    // print the minimum cost     document.write("minimum "+min_sum+"<br>");       Â    // print the maximum cost     document.write("maximum "+ max_sum+"<br>");     }      Â    // Driver Code let arr = [3, 2, 1, 4]; let n = arr.length; let k = 2;   Â// Function call find(arr,n,k);      Â Â// This code is contributed by unknown2108  Â</script>  | 
('minimum ', 3)
('maximum ', 7)
Time Complexity: O(nlog(n))
Auxiliary Space: O(1)
This article is contributed by Sahil Chhabra. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    








