// 面试题47:礼物的最大价值
// 题目:在一个m×n的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值
// (价值大于0)。你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或
// 者向下移动一格直到到达棋盘的右下角。给定一个棋盘及其上面的礼物,请计
// 算你最多能拿到多少价值的礼物?
static int get_max_gift(const uint32_t* values, uint32_t rows, uint32_t cols)
{
if(values == nullptr || rows <= 0 || cols <= 0)
{
return -1;
}
std::vector<uint32_t> max_value(rows*cols);
for(uint32_t i = 0; i < rows; ++i)
{
for(uint32_t j = 0; j < cols; ++j)
{
uint32_t left = 0;
uint32_t up = 0;
if(i > 0)
{
up = max_value[(i - 1)*cols + j];
}
if(j > 0)
{
left = max_value[i*cols + j - 1];
}
max_value[i*cols + j] = std::max(left, up) + values[i * cols + j];
}
}
return max_value[rows*cols - 1];
}
static int get_max_gift2(const uint32_t* values, uint32_t rows, uint32_t cols)
{
if(values == nullptr || rows <= 0 || cols <= 0)
{
return -1;
}
std::vector<uint32_t> max_value(cols, 0);
for(uint32_t i = 0; i < rows; ++i)
{
for(uint32_t j = 0; j < cols; ++j)
{
uint32_t left = 0;
uint32_t up = 0;
if(i > 0)
{
up = max_value[j];
}
if(j > 0)
{
left = max_value[j - 1];
}
max_value[j] = std::max(left, up) + values[i * cols + j];
}
}
return max_value[cols - 1];
}