using System.Collections.Generic;
public class SubmatrixMaxSumOutput
public List<Index> SubMatrixCoord;
public static SubmatrixMaxSumOutput GetMaxSumInMatrix(int[,] arr)
int N = arr.GetLength(0); int M = arr.GetLength(1);
for (int j = 0; j < M; j++) {
for (int i = 1; i < N; i++) {
arr[i, j] += arr[i - 1, j];
int maxSum = int.MinValue;
List<Index> tempIndexes = new List<Index>(); List<Index> indexes = new List<Index>();
for (int row_1 = 0; row_1 < N; row_1++) {
for (int row_2 = row_1; row_2 < N; row_2++) {
int partSum = 0; tempIndexes.Clear();
for (int k = 0; k < M; k++)
partSum += row_1 > 0 ? arr[row_2, k] - arr[row_1 - 1, k] : arr[row_2, k];
tempIndexes.Add(new Index { Row = row_1 + 1, Col = k + 1 });
tempIndexes.Add(new Index { Row = row_2 + 1, Col = k + 1 });
indexes.Clear(); indexes.AddRange(tempIndexes);
return new SubmatrixMaxSumOutput { MaxSum = maxSum, SubMatrixCoord = indexes };
public static void Main()
Console.WriteLine("UniLecs");
var output = GetMaxSumInMatrix(arr);
Console.WriteLine(string.Format("\nMax Sum = {0}", output.MaxSum));
if (output.SubMatrixCoord.Count > 1)
Index leftUpIndex = output.SubMatrixCoord.FirstOrDefault();
Index rightDownIndex = output.SubMatrixCoord.LastOrDefault();
Console.WriteLine(string.Format(
"SubMatrix coordinates: ({0}, {1}) - ({2}, {3})\n",
leftUpIndex.Row, leftUpIndex.Col,
rightDownIndex.Row, rightDownIndex.Col));