题解 | #礼物的最大价值#
礼物的最大价值
http://www.nowcoder.com/practice/2237b401eb9347d282310fc1c3adb134
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param grid int整型二维数组
* @return int整型
*/
public int maxValue (int[][] grid) {
// write code here
int row = grid.length;
int col = grid[0].length;
if(row == 1 && col == 1){
return grid[0][0];
}
int [][] maxSum = new int [row][col]; //当前坐标礼物的最大值数组
for(int i = 0; i < row; i++){
label: for(int j = 0; j < col; j++){
if (i == 0 && j == 0){
maxSum[i][j] = grid[i][j]; //特殊情况1:首行首列
continue label;
}
if (i == 0){
maxSum[i][j] = maxSum[i][j - 1] + grid[i][j]; //特殊情况2:首行
continue label;
}
if (j == 0){
maxSum[i][j] = maxSum[i - 1][j] + grid[i][j];//特殊情况3:首列
continue label;
}
maxSum[i][j] = Math.max(maxSum[i - 1][j], maxSum[i][j -1]) + grid[i][j];//普通情况的求解
}
}
return maxSum[row - 1][col - 1];
}
}