leetcode algorithm 807. Max Increase to Keep City Skyline

问题描述

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?

Example:
Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Explanation:
The grid is:
[ [3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0] ]

The skyline viewed from top or bottom is: [9, 4, 8, 7]
The skyline viewed from left or right is: [8, 7, 9, 3]

The grid after increasing the height of buildings without affecting skylines is:

gridNew =
[ [8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3] ]

理解

题目大致意思是一个n*n二维数组中的每一项看作一栋楼,每一栋楼有一定的高度(0-100),从前(后)方看这一片楼盘时只能看到每一列最高的楼,从左(右)看时只能看到每一行最高的楼。现在需要将所有的楼增高,但增高后这一片楼从各方位看到的最高楼的高度不变,求能增高的总高度的最大值。
求出每一行每一列的最大值,比较位于i,j处楼第i行最大值和第j列的最大值,较小的数为该楼可增至的最大高度。

代码

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {
        int[] maxOfIj = new int[2 * grid.length + 1];
        int index = 0;
        int totalIncrease = 0;
        //寻找每一行的最大值
        for(int i = 0;i < grid.length;i++){
            int tempMax = 0;
            for(int j = 0;j < grid.length;j++){
                if(grid[i][j] >= tempMax)
                    tempMax = grid[i][j];
            }
            maxOfIj[index++] = tempMax;
        }
        //寻找每一列的最大值
        for(int j = 0;j < grid.length;j++){
            int tempMax = 0;
            for(int i = 0;i < grid.length;i++){
                if(grid[i][j] >= tempMax)
                    tempMax = grid[i][j];
            }
            maxOfIj[index++] = tempMax;
        }
        //maxOfIj[]中存放着每一行每一列的最大值
        for(int i = 0;i < grid.length;i++){
            for(int j = 0;j < grid.length;j++){
                if(maxOfIj[i] <= maxOfIj[grid.length + j])
                    totalIncrease += (maxOfIj[i] - grid[i][j]);
                else
                    totalIncrease += (maxOfIj[grid.length + j] - grid[i][j]);
                    
            }
            
        }
        return totalIncrease;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值