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?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

具體代碼實現能夠參考Githubui

相關文章
相關標籤/搜索