经典DP之投资者问题
转载请注明作者与出处: franciscolv http://www.cnblogs.com/franciscolv/archive/2011/11/20/2256154.html
package SortSet;
/**
* 投资问题 m万元,n项投资计划 计算最大盈利和
* 示例中行表示m万元,列从第一列开始表示n想投资计划
* @author franciscolv
*
*/
public class InvestProblem {
public static void main(String[] args) {
int[][] a = { { 0, 0, 0, 0, 0 },
{ 1, 11, 0, 2, 20 },
{ 2, 12, 5, 10, 21 },
{ 3, 13, 10, 30, 22 },
{ 4, 14, 15, 32, 23 },
{ 5, 15, 20, 40, 24 } };
System.out.println(getMaxProfits(a, 5, 4));
}
/**
* n*m个问题个子问题 每个问题m种选择 故O(n*m^2)
*/
public static int getMaxProfits(int[][] a, int m, int n) {
int[][] f = new int[m + 1][n + 1];
for(int i=0;i<=m;i++)
f[i][0]=i;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
if (i == 1&&j==1)
f[i][j] = a[1][1];
else {
f[i][j] = findmax(i, j, a, f);
}
}
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++)
System.out.print(f[i][j] + " ");
System.out.println();
}
return f[m][n];
}
/**
* o(m)
*/
private static int findmax(int i, int j, int[][] a, int[][] f) {
int max = -1;
for (int k = 0; k <= i; k++) {
if (a[k][j] + f[i - k][j - 1] > max)
max = a[k][j] + f[i - k][j - 1];
}
return max;
}
}