CS-Notes/notes/47. 礼物的最大价值.md
2019-11-02 12:07:41 +08:00

43 lines
1.2 KiB
Java
Raw 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];
}
```
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-1.png"></img></div>