LeetCode之Max Increase to Keep City Skyline(Kotlin)

本文介绍了一种算法,可在不改变城市从四个方向观看的天际线轮廓的前提下,最大化增加建筑物的高度。通过获取每行每列的最大高度来确定可以增加的高度,并最终实现了这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:
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))
}

有问题随时沟通

具体代码实现可以参考Github

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值