Problem of the day
Ninja is having some health issues. So he decided to buy fruits to get nutrition. There are ‘N’ number of fruits. Each fruit has some amount of nutrition and a specific cost.
Ninja has ‘M’ units of money. You need to find the maximum amount of nutrition Ninja can get and the total cost to get maximum nutrition. The ninja can buy any number of fruits, but he can spend only at most ‘M’ units of money.
Note: If there are multiple values of costs possible for maximum nutrition, you need to find the minimum one.
Example:Suppose there are 3 fruits with costs 1, 2, 3 and nutrition 2, 2, 3 units respectively. Ninja has 3 units of money. Then, the ninja can take fruits with costs 1 and 2, having the maximum nutritional value of 4 units for a cost of 3 units.
The first line contains ‘T,’ denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘M’ and ‘N’, denoting the amount of money ninja has and the total number of fruits.
The next ‘N’ line contains two space-separated integers, ‘X’ and ‘Y’, denoting each fruit's cost and nutrition value.
Output Format :
Print two space-separated integers the maximum amount of nutrition Ninja can get and the total cost to get maximum nutrition.
Note :
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= N <= 1000
1 < = M <=1000
0 < = X <= 1000
0 < = Y <= 1000
Time Limit: 1 sec
2
9 4
1 2
2 3
4 5
5 7
6 3
7 4
9 2
11 12
12 8
0 0
For the first test case:-
The ninja can select the fruits at indices ( 0 - based ) 0, 1, and 3, which constitutes 12 units of nutrition and 8 units of cost.
For the second test case:-
The Ninja can not buy any of these fruits so he will have his nutrition as 0 and cost also 0 as well
2
50 10
12 3
15 8
16 9
16 6
10 2
21 9
18 4
12 4
17 8
18 9
50 10
13 8
19 10
16 8
12 9
10 2
12 8
13 5
15 5
11 7
16 2
26 49
32 48
Try all the sets of fruits possible.
We can recursively try out all the possible sets of fruits possible. We can add the nutrition and cost of each fruit we include in the set. We have two options for each fruit either to take it or not. We can recursively try out for both of these options and return the best of them.
When we reach the end of the array, we can simply return the current value of nutrition and cost.
The steps are as follows:-
// Recursive function to find maximum strength
function getMaxNutritionUtil(int index, [FRUIT] FRUITS,int N,
int cost, int nutrition, int M ):
function getMaxNutrition ( [FRUIT] FRUITS, int N, int M):
O( 2N ), Where ‘N’ is the number of fruits.
Each fruit has two choices. A total of N fruits are in the array, so a total of 2N possibilities is there.
Hence The Time complexity is O( 2N ).
O ( N ), Where ‘N’ is the number of fruits.
Extra auxiliary space will be needed for the recursion call stack.
Hence space complexity is O( N ).