剑指 Offer 47. 礼物的最大价值
剑指 Offer 47. 礼物的最大价值
Offer 47
- 题目描述:
- 状态转移方程:
- 空间复杂度优化:
- 复杂度分析:
package com.walegarrett.offer;
/**
* @Author WaleGarrett
* @Date 2020/12/12 9:08
*/
/**
* 输入:
* [
* [1,3,1],
* [1,5,1],
* [4,2,1]
* ]
* 输出: 12
* 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物
*/
/**
* 题解:dp[i][j] = max(dp[i-1][j] + a[i][j], dp[i][j-1] + a[j][j]);
*/
public class Offer_47 {
public int maxValue(int[][] grid) {
int n = grid.length;
int m = grid[0].length;
int [][]dp = new int[n][m];
for(int i = 0; i< n; i++){
for(int j = 0; j< m; j++){
if(i == 0 && j==0){
dp[i][j] = grid[i][j];
} else if(i == 0){
dp[i][j] = dp[i][j-1] + grid[i][j];
}else if(j == 0){
dp[i][j] = dp[i-1][j] + grid[i][j];
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
}
return dp[n-1][m-1];
}
}
Either Excellent or Rusty