LeetCode - 807. Max Increase to Keep City Skyline (JavaScript)

조민수·2024년 7월 3일
0

LeetCode

목록 보기
47/64
post-custom-banner

Medium, 구현

RunTime : 69 ms / Memory : 51.26 MB


문제

There is a city composed of n x n blocks, where each block contains a single building shaped like a vertical square prism. You are given a 0-indexed n x n integer matrix grid where grid[r][c] represents the height of the building located in the block at row r and column c.

A city's skyline is the outer contour formed by all the building when viewing the side of the city from a distance. The skyline from each cardinal direction north, east, south, and west may be different.

We are allowed to increase the height of any number of buildings by any amount (the amount can be different per building). The height of a 0-height building can also be increased. However, increasing the height of a building should not affect the city's skyline from any cardinal direction.

Return the maximum total sum that the height of the buildings can be increased by without changing the city's skyline from any cardinal direction.


풀이

  • 사실 네 방향 전부를 볼 필요는 없고, 이런 문제는 위, 옆 두 방향만 확인하면 된다.
  • 나는 newGrid라는 2차원 배열을 새로 생성해서 값을 채워 넣을 때, 각 가로축과 세로축의 최소들을 집어넣었다.
    • 이후, 원본 배열과 비교해서 값을 도출했다.
var maxIncreaseKeepingSkyline = function(grid) {
    var west = new Array();
    var north = new Array();
    const n = grid.length;

    for(let i = 0; i < n; i++){
        var wtmp = 0;
        var htmp = 0;
        for(let j = 0; j < n; j++){
            wtmp = Math.max(wtmp, grid[i][j]);
            htmp = Math.max(htmp, grid[j][i]);
        }
        west.push(wtmp);
        north.push(htmp);
    }

    var newGrid = Array.from(Array(n), () => Array(n).fill(0));

    for(let i = 0; i < n; i++){
        for(let j = 0; j < n; j++){
            newGrid[i][j] = Math.min(west[i], north[j]);
        }
    }
    var res = 0;
    for(let x = 0; x < n; x++){
        for(let y = 0; y < n; y++){
            res += (newGrid[x][y] - grid[x][y]);
        }
    }
    return res;
};
  • solution을 참고해보니, newGrid를 만들지 않고 즉시 결과값을 갱신해 시간소요를 줄일 수 있었다.
for(let i = 0; i < n;i++) {
        for(let j = 0; j < n; j++) {
            sum += (Math.min(hmax[i], vmax[j]) - grid[i][j])
        }
    }
profile
사람을 좋아하는 Front-End 개발자
post-custom-banner

0개의 댓글