-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxValueOfPresent.java
More file actions
55 lines (33 loc) · 1.24 KB
/
MaxValueOfPresent.java
File metadata and controls
55 lines (33 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package recursion_and_dynamic_programming;
/**
* @Author: Wenhang Chen
* @Description:在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物?
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入:
* [
* [1,3,1],
* [1,5,1],
* [4,2,1]
* ]
* 输出: 12
* 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
* @Date: Created in 8:34 3/17/2020
* @Modified by:
*/
public class MaxValueOfPresent {
public int maxValue(int[][] grid) {
if (grid == null || grid.length < 1) return 0;
for (int i = 1; i < grid.length; i++) grid[i][0] += grid[i - 1][0];
for (int i = 1; i < grid[0].length; i++) grid[0][i] += grid[0][i - 1];
for (int i = 1; i < grid.length; i++) {
for (int j = 1; j < grid[0].length; j++) {
grid[i][j] = Math.max(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
}
}
return grid[grid.length - 1][grid[0].length - 1];
}
}