Maximum candies two friends can eat
Given six integers X, Y, cnt1, cnt2, C1, and C2, where:
- X and Y represent the maximum calories two friends can consume,
- cnt1 and cnt2 are the numbers of two types of candies,
- C1 and C2 are the calories present in each candy of the two types of available candies.
The task is to find the maximum number of candies the two friends can eat.
Input: X = 25, Y = 36, cnt1 = 10, cnt2 = 6, C1 = 5, C2 = 4
Explanation: Candies will be eaten in the following manner.
Friend 1 can eat 5 candies of type 1: 5*5 = 25 <= 25
Friend 2 can eat all 6 candies of type 2 and 2 candies of type 1: 6*4 + 2*5 = 34 <= 36
Thus, total candies = 5 + 6 + 2 = 13.
Input: X = 452, Y = 225, cnt1 = 50, cnt2 = 125, C1 = 20, C2 = 30
Approach: This problem is observation-based and can be solved by using the Greedy Approach and trying all possible combinations of the candies two friends can consume from given cnt1 and cnt2 candies and trying to finish the candies with lower calory value first.
Follow the steps below to solve the given problem.
- If the calorie value of candy 1 is greater than that of candy 2, then swap the calorie values and counts of both the candy types to ensure that the candy type with fewer calories is consumed first.
- Initialize a variable maxCandies with 0, to store the maximum number of candies that can be eaten by the two friends.
- Run a loop from i = 0 to i = cnt1 (number of candies of type 1) to check all possible combinations:
- Check if the calories consumed by friend 1(i*C1) are greater than his maximum calorie capacity(X). If this is the case, further statements are not executed,
- Calculate the number of type 1 candies consumed by friend 2 (candy1_frnd2). It is given by:
- Calculate the calorie capacity of friend 1 and friend 2 which they can still consume (say left_frnd1 and left_frnd2 ). It can be given by:
- Calculate the number of type 2 candies consumed by friend1 and friend2 respectively (say candy2_frnd1 and candy2_frnd2). It can be given by:
- Update the maximum number of candies that can be consumed by the two friends:
- Return the final value stored in maxCandies
Below is the implementation of the above approach:
Time Complexity: O(N), where N represents the type of candies with a lower calorie value.
Auxiliary Space: O(1)
Please Login to comment...