Maximum sum of any submatrix of a Matrix which is sorted row-wise and column-wise
Given a matrix mat[][] whose elements are sorted both row-wise and column-wise. The task is to find the maximum sum of any submatrix from the given matrix mat[][].
Examples:
Input: mat[][] = { {-6, -4, -1}, {-3, 2, 4}, {2, 5, 8}}
Output: 19
Explanation:
The largest submatrix is given by:
2 4
5 8
Input: mat[][] = { {-4, -3}, {-2, -1} }
Output: -1
Explanation:
The sub matrix consisting of the last element i.e., -1 has the largest sum possible.
Naive Approach: The idea is to find the maximum sum rectangle in 2D matrix using the Kadane’s Algorithm. Print the maximum sum obtained.
Time Complexity: O(N2*M2), where N is the number of rows and M is the number of columns
Auxiliary Space: O(N)
Efficient Approach: The idea is to find the maximum sum from bottom cell of the given matrix and use Dynamic Programming to store the maximum sum of any submatrix from bottom cell. Below are the steps:
- Create a dp table dp[][] of size NxM to store the maximum sum ofsubmatrix starting from each cell (i, j).
- Find the sum of the sub-matrix starting from the bottom-right cell (N, M) going up and left and keep updating the maximum sum to dp[][].
- Since the matrix is sorted Row-Wise and Column-Wise the largest sub-matrix sum may start from any point, but will definitely end on bottom-right cell (N, M).
- Below is the relation how the dp table is filled:
DP[i][j] = DP[i+1][j] + DP[i][j+1] – DP[i+1][j+1]
- Hence, find the maximum element in the dp table.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function that finds the maximum // Sub-Matrix Sum int maxSubMatSum(vector<vector< int > > mat) { // Number of rows in the matrix int n = mat.size(); // Number of columns in the matrix int m = mat[0].size(); int i, j; // dp[][] matrix to store the // results of each iteration int dp[n][m]; // Base Case - The largest // element in the matrix dp[n - 1][m - 1] = mat[n - 1][m - 1]; // To stores the final result int res = dp[n - 1][m - 1]; // Find the max sub matrix sum for // the last row for (i = m - 2; i >= 0; i--) { dp[n - 1][i] = mat[n - 1][i] + dp[n - 1][i + 1]; // Check whether the current // sub-array yields maximum sum res = max(res, dp[n - 1][i]); } // Calculate the max sub matrix // sum for the last column for (i = n - 2; i >= 0; i--) { dp[i][m - 1] = mat[i][m - 1] + dp[i + 1][m - 1]; // Check whether the current // sub-array yields maximum sum res = max(res, dp[i][m - 1]); } // Build the dp[][] matrix from // bottom to the top row for (i = n - 2; i >= 0; i--) { for (j = m - 2; j >= 0; j--) { // Update sum at each // cell in dp[][] dp[i][j] = mat[i][j] + dp[i][j + 1] + dp[i + 1][j] - dp[i + 1][j + 1]; // Update the maximum sum res = max(res, dp[i][j]); } } // Return the maximum sum return res; } // Driver Code int main() { // Given matrix mat[][] vector<vector< int > > mat; mat = { { -6, -4, -1 }, { -3, 2, 4 }, { 2, 5, 8 } }; // Function Call cout << maxSubMatSum(mat); return 0; } |
Java
// Java program for the above approach class GFG{ // Function that finds the maximum // Sub-Matrix Sum static int maxSubMatSum( int [][]mat) { // Number of rows in the matrix int n = mat.length; // Number of columns in the matrix int m = mat[ 0 ].length; int i, j; // dp[][] matrix to store the // results of each iteration int [][]dp = new int [n][m]; // Base Case - The largest // element in the matrix dp[n - 1 ][m - 1 ] = mat[n - 1 ][m - 1 ]; // To stores the final result int res = dp[n - 1 ][m - 1 ]; // Find the max sub matrix sum for // the last row for (i = m - 2 ; i >= 0 ; i--) { dp[n - 1 ][i] = mat[n - 1 ][i] + dp[n - 1 ][i + 1 ]; // Check whether the current // sub-array yields maximum sum res = Math.max(res, dp[n - 1 ][i]); } // Calculate the max sub matrix // sum for the last column for (i = n - 2 ; i >= 0 ; i--) { dp[i][m - 1 ] = mat[i][m - 1 ] + dp[i + 1 ][m - 1 ]; // Check whether the current // sub-array yields maximum sum res = Math.max(res, dp[i][m - 1 ]); } // Build the dp[][] matrix from // bottom to the top row for (i = n - 2 ; i >= 0 ; i--) { for (j = m - 2 ; j >= 0 ; j--) { // Update sum at each // cell in dp[][] dp[i][j] = mat[i][j] + dp[i][j + 1 ] + dp[i + 1 ][j] - dp[i + 1 ][j + 1 ]; // Update the maximum sum res = Math.max(res, dp[i][j]); } } // Return the maximum sum return res; } // Driver Code public static void main(String[] args) { // Given matrix mat[][] int [][]mat= {{ - 6 , - 4 , - 1 }, { - 3 , 2 , 4 }, { 2 , 5 , 8 } }; // Function Call System.out.print(maxSubMatSum(mat)); } } // This code is contributed by Rohit_ranjan |
Python3
# Python3 program for the above approach # Function that finds the maximum # Sub-Matrix Sum def maxSubMatSum(mat): # Number of rows in the matrix n = len (mat) # Number of columns in the matrix m = len (mat[ 0 ]) # dp[][] matrix to store the # results of each iteration dp = [[ 0 ] * m for _ in range (n)] # Base Case - The largest # element in the matrix dp[n - 1 ][m - 1 ] = mat[n - 1 ][m - 1 ] # To stores the final result res = dp[n - 1 ][m - 1 ] # Find the max sub matrix sum for # the last row for i in range (m - 2 , - 1 , - 1 ): dp[n - 1 ][i] = (mat[n - 1 ][i] + dp[n - 1 ][i + 1 ]) # Check whether the current # sub-array yields maximum sum res = max (res, dp[n - 1 ][i]) # Calculate the max sub matrix # sum for the last column for i in range (n - 2 , - 1 , - 1 ): dp[i][m - 1 ] = (mat[i][m - 1 ] + dp[i + 1 ][m - 1 ]) # Check whether the current # sub-array yields maximum sum res = max (res, dp[i][m - 1 ]) # Build the dp[][] matrix from # bottom to the top row for i in range (n - 2 , - 1 , - 1 ): for j in range (m - 2 , - 1 , - 1 ): # Update sum at each # cell in dp[][] dp[i][j] = (mat[i][j] + dp[i][j + 1 ] + dp[i + 1 ][j] - dp[i + 1 ][j + 1 ]) # Update the maximum sum res = max (res, dp[i][j]) # Return the maximum sum return res # Driver Code if __name__ = = '__main__' : # Given matrix mat[][] mat = [ [ - 6 , - 4 , - 1 ], [ - 3 , 2 , 4 ], [ 2 , 5 , 8 ] ] # Function call print (maxSubMatSum(mat)) # This code is contributed by mohit kumar 29 |
C#
// C# program for the above approach using System; class GFG{ // Function that finds the maximum // Sub-Matrix Sum static int maxSubMatSum( int [,]mat) { // Number of rows in the matrix int n = mat.GetLength(0); // Number of columns in the matrix int m = mat.GetLength(1); int i, j; // [,]dp matrix to store the // results of each iteration int [,]dp = new int [n, m]; // Base Case - The largest // element in the matrix dp[n - 1, m - 1] = mat[n - 1, m - 1]; // To stores the readonly result int res = dp[n - 1, m - 1]; // Find the max sub matrix sum for // the last row for (i = m - 2; i >= 0; i--) { dp[n - 1, i] = mat[n - 1, i] + dp[n - 1, i + 1]; // Check whether the current // sub-array yields maximum sum res = Math.Max(res, dp[n - 1,i]); } // Calculate the max sub matrix // sum for the last column for (i = n - 2; i >= 0; i--) { dp[i, m - 1] = mat[i, m - 1] + dp[i + 1, m - 1]; // Check whether the current // sub-array yields maximum sum res = Math.Max(res, dp[i, m - 1]); } // Build the [,]dp matrix from // bottom to the top row for (i = n - 2; i >= 0; i--) { for (j = m - 2; j >= 0; j--) { // Update sum at each // cell in [,]dp dp[i, j] = mat[i, j] + dp[i, j + 1] + dp[i + 1, j] - dp[i + 1, j + 1]; // Update the maximum sum res = Math.Max(res, dp[i, j]); } } // Return the maximum sum return res; } // Driver Code public static void Main(String[] args) { // Given matrix [,]mat int [,]mat= {{ -6, -4, -1 }, { -3, 2, 4 }, { 2, 5, 8 } }; // Function Call Console.Write(maxSubMatSum(mat)); } } // This code is contributed by Rohit_ranjan |
Javascript
<script> // Javascript program for the above approach // Function that finds the maximum // Sub-Matrix Sum function maxSubMatSum(mat) { // Number of rows in the matrix var n = mat.length; // Number of columns in the matrix var m = mat[0].length; var i, j; // dp matrix to store the // results of each iteration var dp = Array(n).fill().map(() => Array(m).fill(0)); // Base Case - The largest // element in the matrix dp[n - 1][m - 1] = mat[n - 1][m - 1]; // To stores the final result var res = dp[n - 1][m - 1]; // Find the max sub matrix sum for // the last row for (i = m - 2; i >= 0; i--) { dp[n - 1][i] = mat[n - 1][i] + dp[n - 1][i + 1]; // Check whether the current // sub-array yields maximum sum res = Math.max(res, dp[n - 1][i]); } // Calculate the max sub matrix // sum for the last column for (i = n - 2; i >= 0; i--) { dp[i][m - 1] = mat[i][m - 1] + dp[i + 1][m - 1]; // Check whether the current // sub-array yields maximum sum res = Math.max(res, dp[i][m - 1]); } // Build the dp matrix from // bottom to the top row for (i = n - 2; i >= 0; i--) { for (j = m - 2; j >= 0; j--) { // Update sum at each // cell in dp dp[i][j] = mat[i][j] + dp[i][j + 1] + dp[i + 1][j] - dp[i + 1][j + 1]; // Update the maximum sum res = Math.max(res, dp[i][j]); } } // Return the maximum sum return res; } // Driver Code // Given matrix mat var mat = [ [ -6, -4, -1 ], [ -3, 2, 4 ], [ 2, 5, 8 ] ]; // Function Call document.write(maxSubMatSum(mat)); // This code contributed by umadevi9616 </script> |
19
Time Complexity: O(N*M), where N is the number of rows and M is the number of columns
Auxiliary Space: O(N*M)