// C# implementation of above approach
using System;
using System.Collections.Generic;
class GFG{
// Stores the dp states
static Dictionary<Tuple<int,
int>, int> dp = new Dictionary<Tuple<int,
int>, int>();
// Recursive Function to calculate the maximum
// prefix sum obtained by merging two arrays
static int maxPreSum(int[] a, int[] b, int x, int y)
{
// If subproblem is already computed
if (dp.ContainsKey(new Tuple<int, int>(x, y)))
return dp[new Tuple<int, int>(x, y)];
// If x >= N or y >= M
if (x == a.Length && y == b.Length)
return 0;
int curr = 0;
if (dp.ContainsKey(new Tuple<int, int>(x, y)))
{
curr = dp[new Tuple<int, int>(x, y)];
}
// If x < N
if (x == a.Length)
{
curr = Math.Max(curr, b[y] + maxPreSum(
a, b, x, y + 1));
}
// If y<M
else if (y == b.Length)
{
curr = Math.Max(curr, a[x] + maxPreSum(
a, b, x + 1, y));
}
// Otherwise
else
{
int max = Math.Max(a[x] + maxPreSum(a, b, x + 1, y),
b[y] + maxPreSum(a, b, x, y + 1));
curr = Math.Max(curr, max);
}
dp[new Tuple<int,int>(x, y)] = curr;
return dp[new Tuple<int, int>(x, y)];
}
// Driver code
static void Main()
{
int[] A = { 2, 1, 13, 5, 14 };
int[] B = { -1, 4, -13 };
Console.WriteLine(maxPreSum(A, B, 0, 0));
}
}
// This code is contributed by divyesh072019