LeetCode之Max|LeetCode之Max Increase to Keep City Skyline(Kotlin)
问题:【LeetCode之Max|LeetCode之Max Increase to Keep City Skyline(Kotlin)】方法:
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): Int {
val skyLine = mutableMapOf()
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) {
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))
}
有问题随时沟通
具体代码实现可以参考Github
推荐阅读
- PMSJ寻平面设计师之现代(Hyundai)
- 太平之莲
- 闲杂“细雨”
- 七年之痒之后
- 深入理解Go之generate
- 由浅入深理解AOP
- 期刊|期刊 | 国内核心期刊之(北大核心)
- 生活随笔|好天气下的意外之喜
- 感恩之旅第75天
- python学习之|python学习之 实现QQ自动发送消息