Find Max sum in a 2D array | PROGRAMMING INTERVIEWS
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:
In this algorithm we calculate the prefix sum for all possible row combination in O(n2) and then take out their maximum contigous sum in O(n) time. Thus doing the task in O(n3) time.
http://www.shuatiblog.com/blog/2014/08/01/Max-Sum-In-2D-Array/
from column level:
Basically, kadane's algorithm (complexity: O(n)) is used inside a naive maximum sum sub-array problem (complexity: O(n2)).
This gives a total complexity of O(n3)
public static double max1DSubarray(double[] array, MutableInt returnStart, MutableInt returnEnd)
{
double max_so_far = 0;
double max_ending_here = 0;
int currentStart = 0;
for (int i = 0; i < array.length; i++)
{
max_ending_here = max_ending_here + array[i];
if (max_ending_here > 0)
{
if (max_ending_here > max_so_far)
{
max_so_far = max_ending_here;
returnStart.setValue(currentStart);
returnEnd.setValue(i);
}
}
else
{
currentStart = i + 1;
max_ending_here = 0;
}
}
return max_so_far;
}
int findMaxSum (int matrix[numRows][numCols])
{
int maxSum=0;
for (int left = 0; left < numCols; left++)
{
int temp[numRows] = {0};
for (int right = left; right < numCols; right++)
{
// Find sum of every mini-row between left and right columns and save it into temp[]
for (int i = 0; i < numRows; ++i)
temp[i] += matrix[i][right];
// Find the maximum sum subarray in temp[].
int sum = kadane(temp, numRows);
if (sum > maxSum)
maxSum = sum;
}
}
return maxSum;
}
=====>
public static double max2DSubarray(double[][] array, MutableInt returnStartX, MutableInt returnStartY, MutableInt returnEndX, MutableInt returnEndY)
{
int rows = array.length, columns = array[0].length;
double max_so_far = -1, max_ending_here = 0;
for (int row1 = 0; row1 < rows; row1++)
{
double[] tmp = new double[columns];
for (int column = 0; column < columns; column++)
{
tmp[column] = 0;
}
for (int row2 = row1; row2 < rows; row2++)
{
for (int column = 0; column < columns; column++)
{
tmp[column] += array[row2][column];
}
MutableInt tmpStartY = new MutableInt(-1), tmpEndY = new MutableInt(-1);
max_ending_here = max1DSubarray(tmp, tmpStartY, tmpEndY);
if (max_ending_here > max_so_far)
{
returnStartX.setValue(row1);
returnEndX.setValue(row2);
returnStartY.setValue(tmpStartY.intValue());
returnEndY.setValue(tmpEndY.intValue());
max_so_far = max_ending_here;
}
}
}
return max_so_far;
}
https://github.com/kevindra/Problems/blob/master/array/MaxSubMatrixSum.cpp
Different solution
The trick is to apply Kadane's algorithm on a 2D matrix. We will consider all the possible 2D matrices which are starting from 0th column and treat them as 1D arrays.
O(N^4)
Also check
https://plus.google.com/+JefferyYuanLifeLongProgrammer/posts/DScjK4y7iAr
http://comeoncodeon.wordpress.com/2009/04/07/maximum-subarray-in-1-d-and-2-d-array/
Read full article from Find Max sum in a 2D array | PROGRAMMING INTERVIEWS
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:
- Traverse matrix at row level.
- have a temporary 1-D array and initialize all members as 0.
- 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.
In this algorithm we calculate the prefix sum for all possible row combination in O(n2) and then take out their maximum contigous sum in O(n) time. Thus doing the task in O(n3) time.
http://www.shuatiblog.com/blog/2014/08/01/Max-Sum-In-2D-Array/
- Traverse matrix at row level.
- have a temporary 1-D array and initialize all members as 0.
- For each row do following
- add value in temporary array for all rows below current row
- apply 1-D kadane on temporary array
- if your current result is greater than current maximum sum, update.
public int maxSum(int[][] A) {
int m = A.length;
int n = A[0].length;
int maxResult = Integer.MIN_VALUE;
for (int i = 0; i < m; i++) {
int[] temp = new int[n];
for (int j = i; j < m; j++) {
// from row#i to row#(m-1), add the number into temp[]
for (int k = 0; k < n; k++) {
temp[k] += A[j][k];
}
// find max sum for 1D array
maxResult = Math.max(maxResult, maxSum(temp));
}
}
return maxResult;
}
private int maxSum(int[] B) {
int sumSoFar = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < B.length; i++) {
maxSum = Math.max(maxSum, sumSoFar + B[i]);
sumSoFar = Math.max(0, sumSoFar + B[i]);
}
return maxSum;
}
http://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_07_-_Submatrix_with_largest_sum.jspfrom column level:
Basically, kadane's algorithm (complexity: O(n)) is used inside a naive maximum sum sub-array problem (complexity: O(n2)).
This gives a total complexity of O(n3)
public static double max1DSubarray(double[] array, MutableInt returnStart, MutableInt returnEnd)
{
double max_so_far = 0;
double max_ending_here = 0;
int currentStart = 0;
for (int i = 0; i < array.length; i++)
{
max_ending_here = max_ending_here + array[i];
if (max_ending_here > 0)
{
if (max_ending_here > max_so_far)
{
max_so_far = max_ending_here;
returnStart.setValue(currentStart);
returnEnd.setValue(i);
}
}
else
{
currentStart = i + 1;
max_ending_here = 0;
}
}
return max_so_far;
}
int findMaxSum (int matrix[numRows][numCols])
{
int maxSum=0;
for (int left = 0; left < numCols; left++)
{
int temp[numRows] = {0};
for (int right = left; right < numCols; right++)
{
// Find sum of every mini-row between left and right columns and save it into temp[]
for (int i = 0; i < numRows; ++i)
temp[i] += matrix[i][right];
// Find the maximum sum subarray in temp[].
int sum = kadane(temp, numRows);
if (sum > maxSum)
maxSum = sum;
}
}
return maxSum;
}
=====>
public static double max2DSubarray(double[][] array, MutableInt returnStartX, MutableInt returnStartY, MutableInt returnEndX, MutableInt returnEndY)
{
int rows = array.length, columns = array[0].length;
double max_so_far = -1, max_ending_here = 0;
for (int row1 = 0; row1 < rows; row1++)
{
double[] tmp = new double[columns];
for (int column = 0; column < columns; column++)
{
tmp[column] = 0;
}
for (int row2 = row1; row2 < rows; row2++)
{
for (int column = 0; column < columns; column++)
{
tmp[column] += array[row2][column];
}
MutableInt tmpStartY = new MutableInt(-1), tmpEndY = new MutableInt(-1);
max_ending_here = max1DSubarray(tmp, tmpStartY, tmpEndY);
if (max_ending_here > max_so_far)
{
returnStartX.setValue(row1);
returnEndX.setValue(row2);
returnStartY.setValue(tmpStartY.intValue());
returnEndY.setValue(tmpEndY.intValue());
max_so_far = max_ending_here;
}
}
}
return max_so_far;
}
- find_max_sum(int input[M][N])
- {
- int tmp[100], n, x1, x2;
- int cur, max_sum, fx1, fx2, fy1, fy2;
- int i,j,k;
- fx1 = fx2 = fy1 = fy2 = max_sum = cur = -1;
- for (i=0; i< M; i++)
- {
- for(k=0; k<N; k++)
- tmp[k] = 0;
- for (j=i; j<M; j++)
- {
- for(k=0; k<N; k++)
- tmp[k] += input[j][k];
- kadane(tmp, N, x1, x2, cur);
- if (cur > max_sum)
- {
- fy1 = x1;
- fy2 = x2;
- fx1 = i;
- fx2 = j;
- max_sum = cur;
- }
- }
- }
- cout << "max Sum = " << max_sum << " from (" << fx1 << "," << fy1 << ") to ("
- << fx2 << "," << fy2 << ")" << endl;
- }
- 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;
- }
- }
- }
https://github.com/kevindra/Problems/blob/master/array/MaxSubMatrixSum.cpp
Different solution
The trick is to apply Kadane's algorithm on a 2D matrix. We will consider all the possible 2D matrices which are starting from 0th column and treat them as 1D arrays.
int
getMaxSubmatSum2(
int
a[][COL],
int
r,
int
c) {
int
globalmax = 0;
for
(
int
i = 0; i < r; i++)
for
(
int
j = i; j < r; j++) {
int
localmax = 0;
for
(
int
k = 0; k < c; k++) {
localmax = max(localmax + getSubmatSum(i, k, j, k), 0);
globalmax = max(localmax, globalmax);
}
}
return
globalmax;
}
int
getMaxSubmatSum(
int
a[][COL],
int
r,
int
c) {
int
maxsum = 0;
for
(
int
r1 = 0; r1 < r; r1++) {
for
(
int
c1 = 0; c1 < c; c1++) {
for
(
int
r2 = r1; r2 < r; r2++) {
for
(
int
c2 = c1; c2 < c; c2++) {
int
sum = getSubmatSum(r1, c1, r2, c2);
maxsum = max(sum, maxsum);
}
}
}
}
return
maxsum;
}
https://plus.google.com/+JefferyYuanLifeLongProgrammer/posts/DScjK4y7iAr
http://comeoncodeon.wordpress.com/2009/04/07/maximum-subarray-in-1-d-and-2-d-array/
Read full article from Find Max sum in a 2D array | PROGRAMMING INTERVIEWS