// C# code to implement the approach
using System;
using System.Linq;
public class GFG {
// dp table initialized with -1
static int[, , ] dp = new int[501, 101, 101];
// Recursive Function to minimize the
// operations to collect at least sum of M
static int Solve(int i, int j, int k, int[] A, int[] B,
int N)
{
// Base case
if (i <= 0) {
return 0;
}
// If answer for current state is
// already calculated then just
// return dp[i][j][k]
if (dp[i, j, k] != -1) {
return dp[i, j, k];
}
// Answer initialized with zero
int ans = (int)1e9;
// Calling recursive function for
// taking j'th element of array A[]
if (j != N) {
ans = Math.Min(
ans,
Solve(i - A[j], j + 1, k, A, B, N) + 1);
}
// Calling recursive function for
// taking k'th element of array B[]
if (k != N) {
ans = Math.Min(
ans,
Solve(i - B[k], j, k + 1, A, B, N) + 1);
}
// Save and return dp value
return dp[i, j, k] = ans;
}
// Function to minimize the operations
// to collect at least sum of M
static int MinOperations(int[] A, int[] B, int N, int M)
{
// Filling dp table with - 1
for (int i = 0; i < dp.GetLength(0); i++) {
for (int j = 0; j < dp.GetLength(1); j++) {
for (int k = 0; k < dp.GetLength(2); k++) {
dp[i, j, k] = -1;
}
}
}
// Minimum operations
int ans = Solve(M, 0, 0, A, B, N);
return ans;
}
static public void Main()
{
// Code
// Input 1
int[] A = { 1, 9, 1, 4, 0, 1 },
B = { 3, 2, 1, 5, 9, 10 };
int N = A.Length;
int M = 12;
// Function Call
Console.WriteLine(MinOperations(A, B, N, M));
// Input 2
int[] A1 = { 0, 1, 2, 3, 5 }, B1
= { 5, 0, 0, 0, 9 };
int N1 = A1.Length;
int M1 = 6;
// Function Call
Console.WriteLine(MinOperations(A1, B1, N1, M1));
}
}
// This code is contributed by lokeshmvs21.