Skip to content

807. Max Increase to Keep City Skyline 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
    const int n = grid.size();
    int ans = 0;
    vector<int> rowMax(n);
    vector<int> colMax(n);

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        rowMax[i] = max(rowMax[i], grid[i][j]);
        colMax[j] = max(colMax[j], grid[i][j]);
      }

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        ans += min(rowMax[i], colMax[j]) - grid[i][j];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  public int maxIncreaseKeepingSkyline(int[][] grid) {
    final int n = grid.length;
    int ans = 0;
    int[] rowMax = new int[n];
    int[] colMax = new int[n];

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        rowMax[i] = Math.max(rowMax[i], grid[i][j]);
        colMax[j] = Math.max(colMax[j], grid[i][j]);
      }

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j)
        ans += Math.min(rowMax[i], colMax[j]) - grid[i][j];

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def maxIncreaseKeepingSkyline(self, grid: list[list[int]]) -> int:
    rowMax = list(map(max, grid))
    colMax = list(map(max, zip(*grid)))
    return sum(min(i, j) for i in rowMax for j in colMax) - sum(map(sum, grid))