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.
Print two space-separated integers the maximum amount of nutrition Ninja can get and the total cost to get maximum nutrition.
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
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.
// Recursive function to find maximum strength
function getMaxNutritionUtil(int index, [FRUIT] FRUITS,int N,
function getMaxNutrition ( [FRUIT] FRUITS, int N, int M):
We can use the memoization technique to store the result for each state with a particular ‘index’ and ‘cost.’ This way, we can save time from recalculating the already calculated results.
For memoization, let us define a 2-dimensional matrix DP of size (N+1) * ( M + 1 ).
Where DP[ i ] [ j ] denotes the best possible values of nutrition and cost for index from ‘i’ to ‘N’ - 1 having already spent ‘j’ units of money.
The idea is the same as memoization. Here, we can use the idea of iterative dynamic programming. Let us define a 2-dimensional matrix DP of size (N+1) * ( M + 1 ).
Where DP[ i ] [ j ] denotes the best possible values of nutrition and cost for index from ‘i’ to ‘N’ - 1 having already spent ‘j’ units of money.
We have two options for each fruit when to take it or not. We can try out both of these options and store the best answer in the ‘DP’ matrix.