807. Max Increase to Keep City Skyline

้€™้กŒๅ…ถๅฏฆๆœƒ็™ผ็พ ็œ‹ๅ››ๅ€‹ๆ–นๅ‘ๆ˜ฏๅคš้ค˜็š„, ็œ‹ๅ…ถไธญๅ…ฉๅ€‹ๆ–นๅ‘ๅฐฑๅฏไปฅ ๏ผˆๅ…ถไป–ๅ…ฉๅ€‹ skyline ๆœƒไธ€ๆจฃ

ไนŸๅฐฑๆ˜ฏ็œ‹ rowMax, colMax ๅณๅฏ , ็„ถๅพŒๆฏไธ€้ปžๅ– min(rowMax, colMax), ๅฐฑๆ˜ฏๆœ€ๅพŒๅปบ็ฏ‰็‰ฉ็š„้ซ˜ๅบฆ๏ผˆไธๅฝฑ้ŸฟๅŽŸๆœฌ skyline)

T: O(n^2)

S: O(n)

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {
        int n = grid.length;
        
        int[] rowMax = 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]);
            }
        }
        int[] colMax = new int[n];
        for (int j = 0; j < n; j++) {
            for (int i = 0; i < n; i++) {
                colMax[j] = Math.max(colMax[j], grid[i][j]);
            }
        }
        int sum = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                sum += (rowMax[i] - grid[i][j]);
                grid[i][j] = rowMax[i];

            }
            //System.out.println(Arrays.toString(grid[i]));
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] >= colMax[j]) {
                    sum += (colMax[j] - grid[i][j]);
                    grid[i][j] = colMax[j];
                }                
            }
            //System.out.println(Arrays.toString(grid[i]));
        }
        
        return sum;
    }
}


/*
west north        east
8     9. 4 8 7.    8 
7                  7 
9                  9
3     9  4 8 7     3



can modify row max and col max

so replace row max first,
the replace col max, if grid value > col max, use min one
 
8487
7477
9487
3333



8
7
9
3
 
 original high
            [3,0,8,4],
            [2,4,5,7],
            [9,2,6,3],
            [0,3,1,0]

increasing height
5 4 0 3  = 12
5 0 2 0  = 7
0 2 2 4  = 8
3 0 2 3  = 8

16 +12+7 = 35 => this q ask for increasing height total


after height
            [8, 4, 8, 7],
            [7, 4, 7, 7],
            [9, 4, 8, 7],
            [3, 3, 3, 3]

*/

ๅ…ถๅฏฆๅช่ฆๅ–่ผƒๅฐ็š„้‚ฃๅ€‹ไพ†็ฎ—ๅฐฑๅฅฝ min(row max, col max), ๅฐฑๆœƒๆ˜ฏ grid[i][j] ไธŠๆœ€ๅพŒ็š„้ซ˜ๅบฆ

Last updated