Leetcode学习笔记:#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?
实现:
public int maxIncreasingKeepingSkyline(int[][] grid){
int n = grid.length;
int[] col = new int[n], row = new int[n];
for(int i = 0; i < n;i++){
for(int j = 0; j < n; j++){
row[i] = Math.max(row[i], grid[i][j]);
col[j] = Math.max(col[j],grid[i][j]);
}
}
int res = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
res += Math.min(row[i],col[j])-grid[i][j];
}
}
return res;
}
思路:
两个数组,第一次遍历用一个保存row行的最大高度,一个保存col列的最大高度。第二次遍历,取row和col中的最小值减去所在位置的高度再加入res中。