![]() |
VOOZH | about |
Prerequisite: Kadane's algorithm
Given a 2D array arr[][] of dimension N*M, the task is to find the maximum sum sub-matrix from the matrix arr[][].
Examples:
Input: arr[][] = {{0, -2, -7, 0 }, { 9, 2, -6, 2 }, { -4, 1, -4, 1 }, { -1, 8, 0, -2}}
Output: 15
Explanation: The submatrix {{9, 2}, {-4, 1}, {-1, 8}} has a sum 15, which is the maximum sum possible.Input: arr[][] = {{1, 2}, {-5, -7}}
Output: 3
Naive Approach: The simplest approach is to generate all possible submatrices from the given matrix and calculate their sum. Finally, print the maximum sum obtained.
Below is the implementation of the above approach:
15
Time Complexity: O(N6)
Auxiliary Space: O(1)
Efficient Approach using Kadane's Algorithm: The above approach can be optimized using the following observations:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
15
Time Complexity: O(N3)
Auxiliary Space: O(N2)
Related Topic: Subarrays, Subsequences, and Subsets in Array