[Sword refers to offer] 47. The greatest value of gifts

Title description

Insert picture description here

Insert picture description here

// 47. 礼物的最大价值


// 力扣
// 在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值
// (价值大于 0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次
// 向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上
// 面的礼物的价值,请计算你最多能拿到多少价值的礼物?

answer

// 题解其实不难,就是动态规划,权衡对哪个方向(左还是上)求和累计的值最大
// 那个方向累计和最大就累加哪个方向的值。
// 本题要的是最大值,而不是路径,我们只需要得到左上到右下的最大值即可。
// 因此同样是动态规划,可以根据动态规划存储方式的不同来优化。

// 力扣
// 本地dp
// 执行用时:3 ms, 在所有 Java 提交中击败了80.03%的用户
// 内存消耗:41.1 MB, 在所有 Java 提交中击败了58.97%的用户
class Solution {
    public int maxValue(int[][] grid) {
        if (grid == null || grid.length == 0)
            return 0;
		int row = grid.length, col = grid[0].length;
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				if (i == 0 && j == 0) 
					continue;
				if (i == 0)
					grid[i][j] += grid[i][j - 1];
				else if (j == 0) 
					grid[i][j] += grid[i - 1][j];
				else
					grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
			}
		}
		return grid[row - 1][col - 1];
    }
}

Schematic diagram:
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Then finally:

Insert picture description here

// 力扣
// 单数组维护dp存储
// 执行用时:2 ms, 在所有 Java 提交中击败了97.66%的用户
// 内存消耗:41.1 MB, 在所有 Java 提交中击败了58.97%的用户
class Solution {
	public int maxValue(int[][] grid) {
		if (grid == null || grid[0].length == 0)
			return 0;
		int col = grid[0].length;
		int[] dp = new int[col];
		for (int[] row : grid) {
			dp[0] += row[0];
			for (int i = 1; i < col; i++) {
				// 如果dp[i]没有赋值,则肯定Math给的是dp[i - 1]
				// 如果dp[i]已经被赋值了,Math.max中的dp[i]为
				// 上一行的i列的dp值。
				dp[i] = Math.max(dp[i], dp[i - 1]) + row[i];
			}
		}
		return dp[col - 1];
	}
}

Schematic diagram:
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Insert picture description here

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/fisherish/article/details/113482291