Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum number of candies that can be bought in C
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 one 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
Syntax
int maxCandies(int arr[], int n);
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
- 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-zero then add this to total.
- If the total is more than the previous bought value then bought=x.
- Return the bought result.
Example
#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<br>", maxCandies(candies, size));
return 0;
}
Total Candies that can be bought: 13
How It Works
The algorithm works backwards from the last candy type. It ensures that for each candy type i, we buy either all available candies or one less than what we bought for type i+1, whichever is smaller. This maintains the constraint that X[j] < X[i] for all j < i.
Conclusion
The greedy approach of working backwards ensures maximum candies can be purchased while satisfying the constraint. The algorithm has O(n) time complexity and O(1) space complexity, making it efficient for large arrays.
