问题: 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?git
方法: 先行遍历获取行方向上的天际线楼高四个,而后列遍历获取列方向上的天际线楼高四个。网格中每一个位置的楼宇能够增长的楼高为该楼宇所在行列的天际线行列楼高的较小值,如i = 1, j = 1位置的楼宇增长楼高不能多于i行天际线楼高和j列天际线楼高的较小值。经过如上方法便可以得到网格中楼宇能够增长的总楼高。github
具体实现:bash
class MaxIncreaseToKeepCitySkyline {
fun maxIncreaseKeepingSkyline(grid: Array<IntArray>): Int {
val skyLine = mutableMapOf<String, Int>()
for (i in grid.indices) {
var rowMax = grid[i][0]
for (j in grid[0].indices) {
if (grid[i][j] > rowMax) {
rowMax = grid[i][j]
}
}
skyLine.put("row$i", rowMax)
}
for (j in grid[0].indices) {
var colMax = grid[0][j]
for (i in grid.indices) {
if (grid[i][j] > colMax) {
colMax = grid[i][j]
}
}
skyLine.put("col$j", colMax)
}
var maxIncrease = 0
for(i in grid.indices) {
for (j in grid[0].indices) {
val skyline = minOf(skyLine["row$i"]!!, skyLine["col$j"]!!)
maxIncrease += (skyline - grid[i][j])
}
}
return maxIncrease
}
}
fun main(args: Array<String>) {
val grid = arrayOf(intArrayOf(3, 0, 8, 4), intArrayOf(2, 4, 5, 7), intArrayOf(9, 2, 6, 3), intArrayOf(0, 3, 1, 0))
val maxIncreaseToKeepCitySkyline = MaxIncreaseToKeepCitySkyline()
print(maxIncreaseToKeepCitySkyline.maxIncreaseKeepingSkyline(grid))
}
复制代码
有问题随时沟通ide