You are on page 1of 1

Following is the code for 1D kadane algorithm.

void kadane(int input[], int n, int &x1, int &x2, int &max)
{
int cur, i;
max = 0;
cur = 0;
x1 = x2 = 0;
int lx1, lx2;
lx1 = 0;
for(int i = 0; i<n; i++)
{
cur = cur+input[i];
if(cur > max)
{
max = cur;
x2 = i;
x1 = lx1;
}
if (cur < 0)
{
cur = 0;
lx1 = i + 1;
}
}
}

Now we can extend this 1D kadane algorithm to 2D kadane algorithm and can find the max sum in
a N*N matrix in O(N^3).

What is needed for extending kadane algorithm is as followed:

1. Traverse matrix at row level.


2. have a temporary 1-D array and initialize all members as 0.
3. For each row do following:
add value in temporary array for all rows below current row (including current
row)
apply 1-D kadane on temporary array
if your current result is greater than current maximum sum, update.
We are actually finding maximum sum sub-matrix by adding continuous rows in the original matrix
and finding maximum value indexes for left and right columns.

You might also like