|
| 1 | +/** |
| 2 | + * 807. Max Increase to Keep City Skyline |
| 3 | + * https://leetcode.com/problems/max-increase-to-keep-city-skyline/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There is a city composed of n x n blocks, where each block contains a single building shaped |
| 7 | + * like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where |
| 8 | + * grid[r][c] represents the height of the building located in the block at row r and column c. |
| 9 | + * |
| 10 | + * A city's skyline is the outer contour formed by all the building when viewing the side of the |
| 11 | + * city from a distance. The skyline from each cardinal direction north, east, south, and west |
| 12 | + * may be different. |
| 13 | + * |
| 14 | + * We are allowed to increase the height of any number of buildings by any amount (the amount can |
| 15 | + * be different per building). The height of a 0-height building can also be increased. However, |
| 16 | + * increasing the height of a building should not affect the city's skyline from any cardinal |
| 17 | + * direction. |
| 18 | + * |
| 19 | + * Return the maximum total sum that the height of the buildings can be increased by without |
| 20 | + * changing the city's skyline from any cardinal direction. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[][]} grid |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var maxIncreaseKeepingSkyline = function(grid) { |
| 28 | + let result = 0; |
| 29 | + const rowMaxes = grid.map(row => Math.max(...row)); |
| 30 | + const columnMaxes = grid.map((row, index) => grid.map(row => row[index])) |
| 31 | + .map(row => Math.max(...row)); |
| 32 | + |
| 33 | + for (let i = 0; i < grid.length; i++) { |
| 34 | + for (let j = 0; j < grid[i].length; j++) { |
| 35 | + const currentHeight = grid[i][j]; |
| 36 | + const minHeight = Math.min( |
| 37 | + Math.max(rowMaxes[i], currentHeight), |
| 38 | + Math.max(columnMaxes[j], currentHeight) |
| 39 | + ); |
| 40 | + |
| 41 | + result += (minHeight - currentHeight); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return result; |
| 46 | +}; |
0 commit comments