807. Max Increase to Keep City Skyline

本文介绍了一个关于二维网格中增加建筑高度的问题,目标是在保持四周天际线不变的情况下,尽可能增加建筑高度并求得总的增加量。文章提供了一种解决方案,通过预先计算每一行和每一列的最大值,并利用这些信息来确定可以增加的高度。

1,题目要求
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?
这里写图片描述
每行都有一个最大值,每列也都有一个最大值。 给每个节点的值增加最大的数量的同时,不会改变该行或该列的最大值。

2,题目思路
对于这道题,经过简化之后,就是在说对于一个方阵,每一行和每一列都有最大值,我们只要求出对应的最大值,然后再遍历这样的方阵,计算对应的元素应该增加的数的总和,就可以得到最后的解。

3,程序源码

class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
    auto n = grid.size();
    vector<int> row_max(n,0), col_max(n,0);
    for(int i = 0;i<n;i++)
        for(int j = 0;j<n;j++)
        {
            row_max[i] = max(row_max[i], grid[i][j]);
            col_max[j] = max(col_max[j], grid[i][j]);
        }

    int res = 0;

    for(int i = 0;i<n;i++)
        for(int j = 0;j<n;j++)
            res += min(row_max[i],col_max[j]) - grid[i][j];

    return res;

}

};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值