using System;
class GfG {
static int findSum(int up, int left, int down, int right, int[,] pref) {
// Start with the sum of the entire submatrix from (0,0) to (down,right)
int sum = pref[down, right];
// Subtract the area to the left of the submatrix, if it exists
if (left - 1 >= 0)
sum -= pref[down, left - 1];
// Subtract the area above the submatrix, if it exists
if (up - 1 >= 0)
sum -= pref[up - 1, right];
// Add back the overlapping area that was subtracted twice
if (up - 1 >= 0 && left - 1 >= 0)
sum += pref[up - 1, left - 1];
return sum;
}
static int maxRectSum(int[,] mat) {
int n = mat.GetLength(0);
int m = mat.GetLength(1);
// Initialize the prefix sum matrix
int[,] pref = new int[n, m];
// Compute row-wise prefix sum
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
pref[i, j] = mat[i, j];
if (j - 1 >= 0)
pref[i, j] += pref[i, j - 1];
}
}
// Compute column-wise prefix sum
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
if (i - 1 >= 0)
pref[i, j] += pref[i - 1, j];
}
}
int maxSum = int.MinValue;
// Check all possible submatrices
for (int up = 0; up < n; up++) {
for (int left = 0; left < m; left++) {
for (int down = up; down < n; down++) {
for (int right = left; right < m; right++) {
int totalSum = findSum(up, left, down, right, pref);
if (totalSum > maxSum)
maxSum = totalSum;
}
}
}
}
return maxSum;
}
static void Main(string[] args) {
int[,] mat = new int[,]
{
{ 1, 2, -1, -4, -20 },
{ -8, -3, 4, 2, 1 },
{ 3, 8, 10, 1, 3 },
{ -4, -1, 1, 7, -6 }
};
Console.WriteLine(maxRectSum(mat));
}
}