![]() |
VOOZH | about |
Given a matrix mat[][] of size M x N where mat[i][j], the task is to find the maximum possible sum by picking contiguous elements from each or from each column.
Note: It is compulsory to pick at least one element from each row or column and you can perform this either in rows only or in columns only.
Examples:
Input: mat[][] = [ [-3, 0, -5, -8], [4, -3, 4, -2], [4, 3, -8, 6], [-1, -1, -1, -1] ]
Output: 21
Explanation: Max amount if moving horizontally = 0(1st row) + 4 - 3 + 4 (2nd row) + 4 + 3 (3rd row) - 1 (4th row) = 0 + 5 + 7 - 1 = 11
Max amount if moving vertically = 4+4 (1st column) + 3 (2nd row) + 4 (3rd row) + 6 (4th row) = 8 + 3 + 4 + 6 = 21
Maximum sum = max(11, 21) = 21Input: mat = [ [-1, -2], [-1, -3] ]
Output: -2
Approach: The problem can be solved using Kadane's Algorithm based on the following idea:
- Store the maximum contiguous sum for each row in a variable row sum
- Store the maximum contiguous sum for each column in a variable col sum
If selecting elements only from row then the sum of row sums will be the maximum sum and if selecting columns only then the sum of columns will be the maximum column. The maximum among these two sums is the required answer.
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach.
21
Time Complexity: O(M * N)
Space Complexity: O(max(M, N))