Input: ‘N’= 4 ‘DISHES’ =[2, 4, 6, 8] ‘INGREDIENTS’=[1, 4, 5, 3]
Output: 7
First dish can be made using 2 ingredients of type 1.
Second using 1 ingredient of type 2.
Third using 2 ingredients of type 4.
Fourth using 2 ingredients of type 2.
So total 7 ingredients.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains one integer ‘N’ denoting the number of dishes and ingredients present.
The second line of each test case contains ‘N’ single space-separated integers, elements of the array ‘DISHES’.
The third line of each test case contains ‘N’ single space-separated integers, elements of the array ‘INGREDIENTS’.
For each test case, Return the minimum number of ingredients to make all dishes.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 500
1 <= N <= 500
1 <= DISHES[i] <= 1000
1 <= INGREDIENTS[i] <= 500
Time Limit: 1 sec
In this approach, we will recursively try out all possible combinations of ingredients for each dish. Function is called with ‘INDEX’ = 0 and ‘targetSpice‘ equal to spiciness of the dish then we have two options either to pick the ingredient of a given index or not pick.
In the case of pick, we have to again call the function with the same index (as we can have multiple ingredients of the same type) with target spiciness reduced by the spiciness of the ingredient.
In case of not pick, we have to call the function with index+1 and the same ‘targetSpice’.
If the value of ‘targetSpice’ becomes 0 after ‘INDEX’ reaches the end of the array then it is a valid combination.
The combination with the minimum total amount of ingredients is chosen. The same process is repeated for all the dishes.
// Recursive function to find minimum ingredients
function getMinIngredients(int n, [int]dishes, [int]ingredients):
The recursive approach discussed before can be optimized using memoization. We can memoize the result for each state with a particular ‘INDEX’ and ‘targetSpice’. In this way we can save time from recalculating the already calculated results.
For memoization let us define a matrix 2 dimensional array ‘DP’ of size ‘N’ x 1000. 1000 is used because at max target value can be 1000 as per the constraints given in the problem.
DP[i][j] - Minimum no. of ingredients needed to make a dish with ‘j’ spiciness using ingredients with index >= i.
// Recursive function to find minimum ingredients
function getMinIngredients(int n, [int]dishes, [int]ingredients):
The idea is the same as memoization. We are going to use the recurrence relation used in memoization. Here we only need a one-dimensional array ‘DP’ for storing the results.
DP[i] - Minimum no. of ingredients to make a dish with spiciness I.