# 剑指Offer-题47（Java版）：礼物的最大价值

$f\left(i,j\right)=max\left(f\left(i-1,j\right),f\left(i,j-1\right)\right)+gift\left[i,j\right]，$

public class MaxValueOfGifts
{
public static void main(String[] args)
{
int[][] values = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
System.out.println(getMaxPathValue(values));  //29
int[][] values1 = {{1, 10, 3, 8}};
System.out.println(getMaxPathValue(values1));  //22
int[][] values2 = {
{1},
{1},
{5},
{3}};
System.out.println(getMaxPathValue(values2));  //10
}

private static int getMaxPathValue(int[][] values)
{
if (values == null) return 0;

int rows = values.length;
if (rows <= 0) return 0;
int cols = values[0].length;
if (cols <= 0) return 0;

int[][] maxValues = new int[rows][cols];
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
int fromLeft = 0; //左边
int fromUp = 0; //上面

if (i > 0)
fromUp = maxValues[i - 1][j];
if (j > 0)
fromLeft = maxValues[i][j - 1];

maxValues[i][j] = Math.max(fromLeft, fromUp) + values[i][j];
}
}
return maxValues[rows - 1][cols - 1];
}
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120