1,题目要求
In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well.
At the end, the “skyline” when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city’s skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example.
What is the maximum total sum that the height of the buildings can be increased?
每行都有一个最大值,每列也都有一个最大值。 给每个节点的值增加最大的数量的同时,不会改变该行或该列的最大值。
2,题目思路
对于这道题,经过简化之后,就是在说对于一个方阵,每一行和每一列都有最大值,我们只要求出对应的最大值,然后再遍历这样的方阵,计算对应的元素应该增加的数的总和,就可以得到最后的解。
3,程序源码
class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
auto n = grid.size();
vector<int> row_max(n,0), col_max(n,0);
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
{
row_max[i] = max(row_max[i], grid[i][j]);
col_max[j] = max(col_max[j], grid[i][j]);
}
int res = 0;
for(int i = 0;i<n;i++)
for(int j = 0;j<n;j++)
res += min(row_max[i],col_max[j]) - grid[i][j];
return res;
}
};