Open In App

C# Program for Maximum sum rectangle in a 2D matrix | DP-27

Improve
Improve
Like Article
Like
Save
Share
Report

Write a C# program for a given 2D array, the task is to find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29.

This problem is mainly an extension of the Largest Sum Contiguous Subarray for 1D array.

C# Program for Maximum sum rectangle in a 2D matrix using Naive Approach:

The Naive Solution for this problem is to check every possible rectangle in the given 2D array. This solution requires 6 nested loops –  

  • 4 for start and end coordinate of the 2 axis O(n4)
  • and 2 for the summation of the sub-matrix O(n2).

Below is the implementation of the above approach:

C#




using System;
 
class GFG {
    // Function to find the maximum sum subrectangle in a
    // given matrix
    static void MaxMatrixSum(int[][] matrix)
    {
        int n
            = matrix.Length; // Number of rows in the matrix
        int m = matrix[0].Length; // Number of columns in
                                  // the matrix
        int maxsum
            = int.MinValue; // Variable to store the maximum
                            // sum found so far
        int top = 0, bottom = 0, left = 0,
            right
            = 0; // Variables to store the coordinates of
                 // the subrectangle with the maximum sum
 
        // Loop for the top row position of the rectangle
        for (int i = 0; i < n; i++) {
            // Loop for the left column position of the
            // rectangle
            for (int j = 0; j < m; j++) {
                // Loop for the bottom row position of the
                // rectangle
                for (int k = i; k < n; k++) {
                    // Loop for the right column position of
                    // the rectangle
                    for (int l = j; l < m; l++) {
                        int curr
                            = 0; // Variable to store the
                                 // current sum of elements
                                 // in the rectangle
 
                        // Nested loops execute for finding
                        // the sum of elements in the
                        // rectangle
                        for (int x = i; x <= k; x++) {
                            for (int y = j; y <= l; y++) {
                                curr += matrix[x][y];
                            }
                        }
 
                        // Updating the resultant variables
                        // if curr > maxsum
                        if (curr > maxsum) {
                            maxsum = curr;
                            top = i;
                            left = j;
                            right = l;
                            bottom = k;
                        }
                    }
                }
            }
        }
 
        // Printing the coordinates and sum of the maximum
        // sum subrectangle
        Console.WriteLine("(Top, Left) (" + top + ", "
                          + left + ")");
        Console.WriteLine("(Bottom, Right) (" + bottom
                          + ", " + right + ")");
        Console.WriteLine("The sum of this rectangle is: "
                          + maxsum);
    }
 
    static void Main()
    {
        int[][] v
            = new int[][] { new int[] { 1, 2, -1, -4, -20 },
                            new int[] { -8, -3, 4, 2, 1 },
                            new int[] { 3, 8, 10, 1, 3 },
                            new int[] { -4, -1, 1, 7,
                                        -6 } };
 
        MaxMatrixSum(v);
    }
}


Output

(Top, Left) (1, 1)
(Bottom, Right) (3, 3)
The sum of this rectangle is: 29

Time Complexity: O(n^3 * m^3) where n is the number of rows and m is the numbr of columns in the given matrix.
Auxiliary space: O(1)

C# Program for Maximum sum rectangle in a 2D matrix using Kadane’s algorithm:

Approach:

  • Fix the left and right columns one by one.
  • Calculate the sum of rows between these columns and store the sums in a temporary array.
  • Apply Kadane’s 1D algorithm to the temporary array to find the maximum sum subarray.
  • Compare this maximum sum with the maximum sum found so far.
  • Repeat steps 1-4 for all possible column pairs.
  • The maximum sum found in step 4 represents the maximum sum subrectangle in the 2D array.
  • This approach reduces the time complexity to O(n^3).

Below is the implementation of the above approach:

C#




// C# Given a 2D array, find the
// maximum sum subarray in it
using System;
 
class GFG {
 
    /**
    * To find maxSum in 1d array
    *
    * return {maxSum, left, right}
    */
    public static int[] kadane(int[] a)
    {
        int[] result = new int[] { int.MinValue, 0, -1 };
        int currentSum = 0;
        int localStart = 0;
 
        for (int i = 0; i < a.Length; i++) {
            currentSum += a[i];
            if (currentSum < 0) {
                currentSum = 0;
                localStart = i + 1;
            }
            else if (currentSum > result[0]) {
                result[0] = currentSum;
                result[1] = localStart;
                result[2] = i;
            }
        }
 
        // all numbers in a are negative
        if (result[2] == -1) {
            result[0] = 0;
            for (int i = 0; i < a.Length; i++) {
                if (a[i] > result[0]) {
                    result[0] = a[i];
                    result[1] = i;
                    result[2] = i;
                }
            }
        }
        return result;
    }
 
    /**
    * To find and print maxSum,
    (left, top),(right, bottom)
    */
    public static void findMaxSubMatrix(int[, ] a)
    {
        int cols = a.GetLength(1);
        int rows = a.GetLength(0);
        int[] currentResult;
        int maxSum = int.MinValue;
        int left = 0;
        int top = 0;
        int right = 0;
        int bottom = 0;
 
        for (int leftCol = 0; leftCol < cols; leftCol++) {
            int[] tmp = new int[rows];
 
            for (int rightCol = leftCol; rightCol < cols;
                rightCol++) {
 
                for (int i = 0; i < rows; i++) {
                    tmp[i] += a[i, rightCol];
                }
                currentResult = kadane(tmp);
                if (currentResult[0] > maxSum) {
                    maxSum = currentResult[0];
                    left = leftCol;
                    top = currentResult[1];
                    right = rightCol;
                    bottom = currentResult[2];
                }
            }
        }
 
        Console.Write("MaxSum: " + maxSum + ", range: [("
                    + left + ", " + top + ")(" + right
                    + ", " + bottom + ")]");
    }
 
    // Driver Code
    public static void Main()
    {
        int[, ] arr = { { 1, 2, -1, -4, -20 },
                        { -8, -3, 4, 2, 1 },
                        { 3, 8, 10, 1, 3 },
                        { -4, -1, 1, 7, -6 } };
 
        // Function call
        findMaxSubMatrix(arr);
    }
}
 
// This code is contributed
// by PrinciRaj1992


Output

MaxSum: 29, range: [(1, 1)(3, 3)]

Time Complexity: O(c*c*r), where c represents the number of columns and r represents the number of rows in the given matrix.
Auxiliary Space: O(r), where r represents the number of rows in the given matrix.

Please refer complete article on Maximum sum rectangle in a 2D matrix | DP-27 for more details!



Last Updated : 10 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads