Given an NxM (N rows and M columns) integer matrix with non-negative values (0..MAX_INT inclusive).
What is the maximum sum from going top left (0, 0) to bottom right (N-1, M-1) ?
The condition is that when you're at point (p, q), you can only move to either right (p, q+1) or down (p+1, q).
Expected time complexity O(N*M)
Expected space complexity O(N+M)
Ans:DP strategy.
about space complexity, need elaborate on it.
package com.zhuyu_deng.test;
public class Test
{
public static void main(String args[])
{
int x[][] = { {1,2,3,4},
{12,13,14,5},
{11,16,15,6},
{10,9,8,7},
};
System.out.println(findOptPath2(x));
}
private static int findOptPath(int[][] x)
{
int d[][] = new int[x.length][x[0].length];
d[0][0] = x[0][0];
for (int i = 1; i < x.length; ++i)
d[i][0] = d[i-1][0] + x[i][0];
for (int i = 1; i < x[0].length; ++i)
d[0][i] = d[0][i-1] + x[i][0];
for (int i = 1; i < x.length; ++i)
{
for (int j = 1; j < x[0].length; ++j)
{
if (d[i-1][j] > d[i][j-1])
d[i][j] = d[i-1][j] + x[i][j];
else
d[i][j] = d[i][j-1] + x[i][j];
}
}
return d[x.length-1][x[0].length-1];
}
}