问题:
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?
方法:
先行遍历获取行方向上的天际线楼高四个,然后列遍历获取列方向上的天际线楼高四个。网格中每个位置的楼宇可以增加的楼高为该楼宇所在行列的天际线行列楼高的较小值,如i = 1, j = 1位置的楼宇增加楼高不能多于i行天际线楼高和j列天际线楼高的较小值。通过如上方法即可以获得网格中楼宇可以增加的总楼高。
具体实现:
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))
}
有问题随时沟通