Wednesday, December 26, 2018

807. Max Increase to Keep City Skyline


For grid[i][j], it can't be higher than the maximun of its row nor the maximum of its col.
So the maximum increasing height for a building at (i, j) is min(row[i], col[j]) - grid[i][j]
Time O(MN)
Space O(M + N)

96.74 %
class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) return 0;
        int rows = grid.length;
        int cols = grid[0].length;
        int[] rowMax = new int[rows];
        int[] colMax = new int[cols];
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                rowMax[y] = Math.max(rowMax[y], grid[y][x]);
                colMax[x] = Math.max(colMax[x], grid[y][x]);
            }
        }
        int result = 0;
        for (int y = 0; y < rows; y++) {
            for (int x = 0; x < cols; x++) {
                result += Math.min(rowMax[y], colMax[x]) - grid[y][x];
            }
        }
        return result;
    }
}

No comments:

Post a Comment