CS-Notes/notes/47. 礼物的最大价值.md
2020-11-17 00:32:18 +08:00

36 lines
1.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 47. 礼物的最大价值
[NowCoder](https://www.nowcoder.com/questionTerminal/72a99e28381a407991f2c96d8cb238ab)
## 题目描述
在一个 m\*n 的棋盘的每一个格都放有一个礼物,每个礼物都有一定价值(大于 0。从左上角开始拿礼物每次向右或向下移动一格直到右下角结束。给定一个棋盘求拿到礼物的最大价值。例如对于如下棋盘
```
1 10 3 8
12 2 9 6
5 7 4 11
3 7 16 5
```
礼物的最大价值为 1+12+5+7+7+16+5=53。
## 解题思路
应该用动态规划求解,而不是深度优先搜索,深度优先搜索过于复杂,不是最优解。
```java
public int getMost(int[][] values) {
if (values == null || values.length == 0 || values[0].length == 0)
return 0;
int n = values[0].length;
int[] dp = new int[n];
for (int[] value : values) {
dp[0] += value[0];
for (int i = 1; i < n; i++)
dp[i] = Math.max(dp[i], dp[i - 1]) + value[i];
}
return dp[n - 1];
}
```