807. Max Increase to Keep City Skyline
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?
Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]
The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]
The grid after increasing the height of buildings without affecting skylines is:
gridNew = [ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]
Notes:
-
1 < grid.length = grid[0].length <= 50
. - All heights
grid[i][j]
are in the range[0, 100]
. - All buildings in
grid[i][j]
occupy the entire grid cell: that is, they are a1 x 1 x grid[i][j]
rectangular prism.
这道题初看的时候觉得很有意思,但想不出具体什么情况下会产生这种需求。我首先想到的是生成那两个数组:从上下看的数组 和 从左右看的数组。然后依据这两个数组更新这个二维数组,这时才发现更新的规则很简单,就是选两个数组相应位置较小的值即可。最后再审一遍题发现题目的最终要求不是更新数组,而是输出这样更新之后二维数组总和比之前大了多少。总的来说这道题还是比较简单的。
Java代码
class Solution {
public int maxIncreaseKeepingSkyline(int[][] grid) {
int result = 0;
int[] topAndBottom = new int[grid[0].length];
int[] leftAndRight = new int[grid.length];
for(int i=0;i<grid[0].length;i++){
topAndBottom[i] = maxOfColumn(grid, i);
}
for(int i=0;i<grid.length;i++){
leftAndRight[i] = maxOfRow(grid, i);
}
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[i].length;j++){
int max = topAndBottom[j]>leftAndRight[i]?leftAndRight[i]:topAndBottom[j];
result += max - grid[i][j];
}
}
return result;
}
private int maxOfColumn(int[][] grid, int ColunmNums){
int max = grid[0][ColunmNums];
for(int i=0;i<grid.length;i++){
if(max<grid[i][ColunmNums]){
max = grid[i][ColunmNums];
}
}
return max;
}
private int maxOfRow(int[][] grid, int RowNums){
int max = grid[RowNums][0];
for(int i=0;i<grid[RowNums].length;i++){
if(max<grid[RowNums][i]){
max=grid[RowNums][i];
}
}
return max;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。