题目描述
在一个mxn的棋盘的每一格都放一个礼物,每个礼物都有一定的价值(价值>0)。你可以从棋盘的左上角开始拿盒子里的礼物,并每次向右或乡下移动一格,知道到达前的右下角。给定一个棋盘及其上面的礼物,请计算你最多能拿到多少的礼物?
例如,沿着下划线的数字的线路(1,、12、5、7、7、16、5),拿到最大价值为53的礼物。
1 10 3 8
12 2 9 6
5 7 4 11
3 7 16 5
实现
方法:动态规划
参考:https://blog.csdn.net/weixin_38361153/article/details/88909186
public class C47_matrix_MaxValue {
static int getMaxVal(int[][] val) {
if (val == null || val.length == 0 || val[0].length == 0) {
return 0;
}
int rows = val.length;
int cols = val[0].length;
int[] maxVal = new int[cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int left = 0;
int up = 0;
if (i > 0) up = maxVal[j];
if (j > 0) left = maxVal[j - 1];
maxVal[j] = Math.max(left, up) + val[i][j];
}
}
return maxVal[cols - 1];
}
}
Test
public static void main(String[] args) {
int[][] arr = {
{ 1, 10, 3, 8 },
{ 12, 2, 9, 6 },
{ 5, 7, 4, 11 },
{ 3, 7, 16, 5 } };
System.out.println(getMaxVal(arr));
}