Open In App

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

Last Updated : 10 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a Java 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.

Java 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:

Java




import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
    public static void maxMatrixSum(int[][] matrix)
    {
        int n = matrix.length; // no of rows in a matrix;
        int m
            = matrix[0].length; // no of columns in matrix;
        int maxsum = -999999999;
        int top = 0, bottom = 0, left = 0, right = 0;
        for (int i = 0; i < n;
            i++) { // This loop for top row position in the
                    // rectangle
            for (int j = 0; j < m;
                j++) { // This loop for left column
                        // position of the rectangle
                for (int k = 0; k < n;
                    k++) { // This loop for bottom row in
                            // the rectangle
                    for (int l = 0; l < m;
                        l++) { // This loop for right
                                // column in the rectangle
 
                        int curr = 0;
                        for (int x = i; x <= k;
                            x++) { // This loops execute
                                    // for finding sum of
                                    // elements in the
                                    // rectangle
                            for (int y = j; y <= l;
                                y++) { // for all possibble
                                        // points of
                                        // rectangle
                                curr += matrix[x][y];
                            }
                        }
                        if (curr > maxsum) {
                            maxsum = curr;
                            top = i;
                            left = j;
                            right = k;
                            bottom = l;
                        }
                    }
                }
            }
        }
        System.out.println("Top , Left ) ( " + top + " , "
                        + left + " )");
        System.out.println("Bottom , Right) ( " + bottom
                        + " , " + right + " )");
        System.out.println("The sum of the rectangle is: "
                        + maxsum);
    }
    public static void main(String[] args)
    {
        int arr[][] = new int[][] { { 1, 2, -1, -4, -20 },
                                    { -8, -3, 4, 2, 1 },
                                    { 3, 8, 10, 1, 3 },
                                    { -4, -1, 1, 7, -6 } };
 
        // Function call
        maxMatrixSum(arr);
    }
}
// contributed by hungry_coder_109(Naveen);


Output

Top , Left ) ( 1 , 1 )
Bottom , Right) ( 3 , 3 )
The sum of the 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)

Java 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:

Java




// Java Program to find max sum rectangular submatrix
 
import java.io.*;
import java.lang.*;
import java.util.*;
 
class MaximumSumRectangle {
 
    // Function to find maximum sum rectangular
    // submatrix
    private static int maxSumRectangle(int[][] mat)
    {
        int m = mat.length;
        int n = mat[0].length;
        int preSum[][] = new int[m + 1][n];
 
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                preSum[i + 1][j] = preSum[i][j] + mat[i][j];
            }
        }
 
        int maxSum = -1;
        int minSum = Integer.MIN_VALUE;
        int negRow = 0, negCol = 0;
        int rStart = 0, rEnd = 0, cStart = 0, cEnd = 0;
        for (int rowStart = 0; rowStart < m; rowStart++) {
            for (int row = rowStart; row < m; row++) {
                int sum = 0;
                int curColStart = 0;
                for (int col = 0; col < n; col++) {
                    sum += preSum[row + 1][col]
                        - preSum[rowStart][col];
                    if (sum < 0) {
                        if (minSum < sum) {
                            minSum = sum;
                            negRow = row;
                            negCol = col;
                        }
                        sum = 0;
                        curColStart = col + 1;
                    }
                    else if (maxSum < sum) {
                        maxSum = sum;
                        rStart = rowStart;
                        rEnd = row;
                        cStart = curColStart;
                        cEnd = col;
                    }
                }
            }
        }
 
        // Printing final values
        if (maxSum == -1) {
            System.out.println("from row - " + negRow
                            + " to row - " + negRow);
            System.out.println("from col - " + negCol
                            + " to col - " + negCol);
        }
        else {
            System.out.println("from row - " + rStart
                            + " to row - " + rEnd);
            System.out.println("from col - " + cStart
                            + " to col - " + cEnd);
        }
        return maxSum == -1 ? minSum : maxSum;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[][] = new int[][] { { 1, 2, -1, -4, -20 },
                                    { -8, -3, 4, 2, 1 },
                                    { 3, 8, 10, 1, 3 },
                                    { -4, -1, 1, 7, -6 } };
 
        // Function call
        System.out.println(maxSumRectangle(arr));
    }
}
 
// This code is contributed by Nayanava De


Output

from row - 1 to row - 3
from col - 1 to col - 3
29

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!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads