2D Kadane To find out the maximum sum sub- matrix in a given matrix
2D Kadane
To find out the maximum sum sub-matrix in a given matrix
Objective
Given a matrix of numbers, we need to find a sub-matrix the sum of whose elements is the maximum of sums of sub-matrices of all possible sizes
Example
9 8 5
6 -1 2
-3 -4 -1
Possible Sub-matrices
1X1
8
6 2
-3 -4
-1
-1
9 5
1X2
9 8
6 -1
-4 -1-3 -4
-1 2
8 5
2X1
5
2
9
6
8
-1
-1
-4
2
-1
6
-3
1X3
-3 -4 -1
6 -1 2
9 8 5
3X1
9
6
-3
8
-1
-4
5
2
-1
2X2
6 -1
-3 -4
-1 2
-4 -1
8 5
-1 2
9 8
6 -1
2X3
6 -1 2
-3 -4 -1
9 8 5
6 -1 2
3X2
9 8
6 -1
-3 -4
8 5
-1 2
-4 -1
3X3
9 8 5
6 -1 2
-3 -4 -1
Of all these sub-matrices
Maximum sum is of the sub-matrix
Its sum is 29
9 8 5
6 -1 2
2D Kadane Intuition
Let us take the same sub-matrix
We will work through it step by step
This is the given matrix
9 8 5
6 -1 2
-3 -4 -1
STEP 1
For each row calculate the sum of elements along the columns from row 1 to row i
For row 1 to 1
The sum is:
9 8 5
For row 1 to 2
Add the elements of the 2 rows
9 8 5
6 -1 2
9+6=15 8-1=7 5+2=7
For row 1 to 3
Add the elements of the three rows
9 8 5
6 -1 2
-3 -4 -1
9+6-3=12 8-1-4=3 5+2-1=6
We have the following 3 rows
9 8 5
12 3 6
15 7 7
STEP 2
For each pair of rows i & j calculate the sum of elements along the columns from row i to row j
Sum of elements from row i to j = (sum from row 1 to j) – (sum from 1 to i-1)
Row 1 to 1 Row 2 to 2
Row 1 to 2 Row 2 to 3
Row 1 to 3 Row 3 to 3
9 8 5
12 3 6
15 7 7
6 -1 2
-3 -4 -1
3 -5 1
STEP 3
To each of the pairwise row sums found in the previous step apply 1D Kadane algorithm to find maximum contiguous sum in each pair-wise row sum. The maximum of all such contiguous sums found is the answer.
Row 1 to 1 – max_sum = 22 for col 1 to 3 Row 2 to 2 – max_sum = 7 for col 1 to 3
Row 1 to 2 – max_sum = 29 for col 1 to 3 Row 2 to 3 – max_sum = 3 for col 1 to 1
Row 1 to 3 – max_sum = 21 for col 1 to 3 Row 3 to 3 – max_sum = -1 for col 3 to 3
9 8 5
12 3 6
15 7 7
6 -1 2
-3 -4 -1
3 -5 1
Maximum sum is for all 3 columns rows 1 and 2
i.e. the max sum sub-matrix is
Maximum sum = 29
9 8 5
6 -1 2
Algorithm
Consider a matrix of dimensions M X N1. For each row i calculate the sum of elements
along the columns from row 1 to row i2. For each pair of rows i and j, calculate the sum
of elements from along the columns from row ito row j. The sums calculated in step 1 are helpful. We get C(M,2) rows
3. For each of the pair-wise row sum calculated in step 2, calculate the maximum sum using 1D Kadane algo.
4. The maximum over all the sum found in step 3 is the required answer.
Complexity
For step 1 of algo: O(MN)
For step 2 of algo: O(NM2)
For step 3 of algo: O(NM2)
Thus overall complexity O(NM2)
Considering N and M to be of the same order complexity is O(N3)