Max Increase to Keep City Skyline - javascript

2021. 2. 2. 17:54알고리즘

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?

 

이중 배열이 주어졌을 때, 아래 그림과 같이 사격형 모양으로 배열을 두고 동서남북으로 바라봤을 때 기존의 가장 높은 건물의 높이를 벗어나지 않도록 작은 건물들의 높이를 얼마만큼 올릴 수 있냐를 구하는 문제였다. arr[i][j]는 해당 건물의 높이로 단순히 해당 row의 최대값만 고려하는 것이 아니라 세로 열도 고려를 해야한다. 

 

 

const maxIncreaseKeepingSkyline = function(grid) {
    let column = [];
    let count = 0;
  // 열의 최대값을 저장하고 비교할 배열을 생성
    for(let i=0; i< grid.length; i++ ){
     let storage = [];
      for(let j= 0; j< grid.length; j++){
       storage.push(grid[j][i]);
     }
     column.push(Math.max.apply(null, storage));
    }
   // 세로 열의 최대값들을 위 과정을 통해서 구한다
   for(let i=0; i < grid[0].length; i++){    
     const rowMaster = Math.max.apply(null, grid[i]);
// 반복문을 돌리면서 각 행에 방문하는데, 이때 해당 행의 최대값을 설정하고 아래 코드를 실행한다.
    for(let j=0; j< grid[0].length; j++){
      if(rowMaster >= column[j]){
        let numA = column[j] - grid[i][j];
        if(numA > 0){
        count += numA;
        }
      }
      else if(rowMaster < column[j]){
        let numB = rowMaster - grid[i][j];
        if(numB > 0){
        count += numB;
        }
      }
    }
       
   }
   return count
};