using System;
class GFG
{
static readonly int R = 5;
static readonly int C = 4;
static bool isValid(int x, int y1, int y2)
{
return (x >= 0 && x < R && y1 >=0 &&
y1 < C && y2 >=0 && y2 < C);
}
static int getMaxUtil(int [,]arr, int [,,]mem,
int x, int y1, int y2)
{
if (!isValid(x, y1, y2)) return int.MinValue;
if (x == R-1 && y1 == 0 && y2 == C-1)
return (y1 == y2)? arr[x, y1]: arr[x, y1] + arr[x, y2];
if (x == R-1) return int.MinValue;
if (mem[x, y1, y2] != -1) return mem[x, y1, y2];
int ans = int.MinValue;
int temp = (y1 == y2)? arr[x, y1]:
arr[x, y1] + arr[x, y2];
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1, y2-1));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1, y2+1));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1, y2));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1-1, y2));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1-1, y2-1));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1-1, y2+1));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1+1, y2));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1+1, y2-1));
ans = Math.Max(ans, temp +
getMaxUtil(arr, mem, x+1, y1+1, y2+1));
return (mem[x, y1, y2] = ans);
}
static int geMaxCollection(int [,]arr)
{
int [,,]mem = new int[R, C, C];
for(int i = 0; i < R; i++)
{
for(int j = 0; j < C; j++)
{
for(int l = 0; l < C; l++)
mem[i, j, l]=-1;
}
}
return getMaxUtil(arr, mem, 0, 0, C-1);
}
public static void Main(String[] args)
{
int [,]arr = {{3, 6, 8, 2},
{5, 2, 4, 3},
{1, 1, 20, 10},
{1, 1, 20, 10},
{1, 1, 20, 10},
};
Console.Write("Maximum collection is " +
geMaxCollection(arr));
}
}