using System;
class GfG {
static int findSum(int r1, int c1, int r2, int c2,
int[, ] pref) {
// Start with the sum of the entire submatrix
// (0, 0) to (r2, c2)
int totalSum = pref[r2, c2];
// Subtract the area to the left of the submatrix,
// if it exists
if (c1 - 1 >= 0) {
totalSum -= pref[r2, c1 - 1];
}
// Subtract the area to the above the submatrix,
// if it exists
if (r1 - 1 >= 0) {
totalSum -= pref[r1 - 1, c2];
}
// Add back the overlapping area
// that was subtracted twice
if (r1 - 1 >= 0 && c1 - 1 >= 0) {
totalSum += pref[r1 - 1, c1 - 1];
}
return totalSum;
}
static int maxSumRectangle(int[, ] mat) {
int n = mat.GetLength(0);
int m = mat.GetLength(1);
// Initialize the prefix sum matrix
int[, ] pref = new int[n, m];
// Row-wise 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];
}
}
}
// Column-wise 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];
}
}
}
// Find the maximum sum rectangle
int maxSum = int.MinValue;
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++) {
// Find the sum of the submatrix
// (up, left) to
// (down, right)
int totalSum = findSum(up, left,
down, right, pref);
// Update maxSum if totalSum >
// maxSum
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.Write(maxSumRectangle(mat));
}
}