Maximum number of candies that can be bought in C

CServer Side ProgrammingProgramming

We are given an array of candies[] of length stored in ‘size’. Each element candies[i] has a number for candies of type i.The goal is to buy as many candies as possible for any amount of money. The conditions are as given −

If you purchase X[i] of type i (0<= X[i] <= candies[i] ), then for all j ( 1<=j<=i ) at least on of the following conditions must be true −

  • X(j) < X(i) ( candies purchased of type j less than of type i )

  • X(j)=0, no candies of type j purchased

Let’s understand with examples.

Input − Arr[] = { 1,3,5,2,6,7 }.

Output − Maximum Candies that can be bought − 16

Explanation − Candies bought of type i { 0,3,5,2,6,0 }

Input − Arr[] = { 5,7,7,3,4 }.

Output − Maximum Candies that can be bought − 10

Explanation − Candies bought of type i { 0,0,7,3,0 }

Approach used in the below program is as follows

  • The integer array candies[] is used to store the number of candies of type i.

  • Variable ‘size’ stores the length of array candies.

  • Function maxCandies(int arr[], int n) is used to return the total number of candies that can be bought.

  • First suppose we bought the last type of candies. bought=arr[n-1]

  • Starting from the second last element, for(i=n-2;i>=0;i--)

  • Variable x stores the amount of candies of current type that can be bought. x=arr[i] or bought-1 whichever is less.

  • If x is non-zeo then add this to total.

  • If the total is more than the previous bought value then bought=x.

  • Return the bought result.

Example

 Live Demo

#include <stdio.h>
int maxCandies(int arr[], int n){
   int bought = arr[n - 1];
   int total = bought;
   // Starting from second last
   for (int i = n - 2; i >= 0; i--) {
      // Amount of candies of the current
      // type that can be bought
      int x = arr[i]<bought-1?arr[i]:bought-1;
      if (x >= 0) {
         total += x;
         bought = x;
      }
   }
   return total;
}
int main(){
   int candies[] = { 1,2,4,3,7 };
   int size = 5;
   printf("Total Candies that can be bought: %d", maxCandies(candies, size));
   return 0;
}

Output

If we run the above code it will generate the following output −

Total Candies that can be bought: 13
raja
Published on 17-Aug-2020 12:19:50
Advertisements