Maintaining the City Skyline

In the two-dimensional array grid, grid[i][j] represents the height of a building located at a certain location. We are allowed to increase the height of any number (the number of different buildings may vary) of buildings. The height 0 is also considered a building.
Finally, the "skyline" observed from all four directions (i.e. top, bottom, left, and right) of the new array must be the same as the skyline of the original array. The skyline of a city is the outer outline formed by all the buildings when viewed from a distance. Please refer to the example below.
What is the maximum total amount by which the building heights 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 the vertical directions (i.e. top, bottom) is: [9, 4, 8, 7] The "skyline" viewed from the horizontal directions (i.e. left, right) is: [8, 7, 9, 3] After increasing the heights of the buildings without affecting the skyline, the new array is as follows: gridNew = [ [8, 4, 8, 7], [7, 4, 7, 7], [9, 4, 8, 7], [3, 3, 3, 3] ]

Solution

/**
 * @param {number[][]} grid
 * @return {number}
 */
var maxIncreaseKeepingSkyline = function(grid) {
    const nL = grid.length;
    const nT = grid.length; // The problem gives grid.length = grid[0].length
    let maxL = Array(nL).fill(0);
    let maxT = Array(nT).fill(0);
    for(let i=0; i<nL; ++i){
        for(let k=0; k<nT; ++k){
            maxL[i] = Math.max(maxL[i], grid[i][k]);
            maxT[k] = Math.max(maxT[k], grid[i][k]);
        }
    }
    let count = 0;
    for(let i=0; i<nL; ++i){
        for(let k=0; k<nT; ++k){
            count = count + Math.min(maxL[i], maxT[k]) - grid[i][k];
        }
    }
    return count;
};

Approach

The basic idea of the problem is to increase each point in the two-dimensional array to the smaller value between the maximum value in the row and the maximum value in the column of the original two-dimensional array. By doing this, we get an increment for each point, and the final result is the sum of all the increments. We first iterate through the two-dimensional array and obtain all the maximum values of rows and columns and store them separately. Then we iterate through the array again, calculating the increment, which is the smaller value between the maximum values of the row and the column minus the current value, and then we add it to the count. After the loop ends, we return count.

Daily Question

https://github.com/WindrunnerMax/EveryDay

Reference

https://leetcode-cn.com/problems/max-increase-to-keep-city-skyline/