807.Max Increase to Keep City Skyline [JavaScript]

本文探讨了在二维网格中,如何通过增加建筑高度来最大化总高度,同时保持从四个方向观察的天际线不变。文章详细介绍了算法思路,通过比较垂直和水平最大高度来确定每个建筑可以增加的最大高度。

摘要生成于 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?

二、题目大意

给定一个二维数组,数组中的元素表示建筑物的高度,请问如何最大限度的增加建筑物们的高度,并且使得四个方向的“天际线”与之前一样。

三、解题思路

这道题目的解题思路很清晰,就是给每个建筑物添加最大的高度,而高度得保证比水平和垂直方向的最大高度都小。

四、代码实现
const maxIncreaseKeepingSkyline = (grid) => {
  let ans = 0
  const row = grid.length
  if (row <= 0) {
    return ans
  }
  const col = grid[0].length

  const vMax = []

  for (let i = 0; i < col; i++) {
    let max = Number.MIN_SAFE_INTEGER
    for (let j = 0; j < row; j++) {
      max = Math.max(max, grid[j][i])
    }
    vMax.push(max)
  }

  const hMax = []

  for (let i = 0; i < row; i++) {
    let max = Number.MIN_SAFE_INTEGER
    for (let j = 0; j < col; j++) {
      max = Math.max(max, grid[i][j])
    }
    hMax.push(max)
  }
  for (let i = 0; i < row; i++) {
    for (let j = 0; j < col; j++) {
      const min = Math.min(vMax[i], hMax[j])
      ans += (min - grid[i][j])
    }
  }
  return ans
}

  如果本文对您有帮助,欢迎关注微信公众号,为您推送更多大前端相关的内容, 欢迎留言讨论,ε=ε=ε=┏(゜ロ゜;)┛。

  您还可以在这些地方找到我:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值