807. Max Increase to Keep City Skyline

807. Max Increase to Keep City Skyline

class Solution {
    public int maxIncreaseKeepingSkyline(int[][] grid) {
     int[] rowMax = new int[grid.length];
     int[] colMax = new int[grid[0].length];

for (int i = 0; i < grid.length; i++){
	int max = grid[i][0];
	for (int j = 1; j  max ){
			max = grid[i][j];
               }
		}
	rowMax[i] = max;

                                           }

for (int j = 0 ; j < grid[0].length; j++){
	int max = grid[0][j];
	for (int i = 0; i  max ){
 max = grid[i][j];
				    }
 }
	colMax[j] = max;
}
int ans = 0;
for (int i = 0; i < grid.length; i++){
	for (int j = 0; j < grid[i].length; j++){
		int min = Math.min(rowMax[i],colMax[j]);
if(grid[i][j] <span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>&lt; min){
    int add = min - grid[i][j];
        ans+= add;
    }
					}
				}
return ans;
}

}

Note:
Write colMax and rowMax in only one loop, instead of two loops

int[] rowMaxes = new int[N];
int[] colMaxes = new int[N];

for (int r = 0; r < N; ++r)
for (int c = 0; c < N; ++c) {
rowMaxes[r] = Math.max(rowMaxes[r], grid[r][c]);
colMaxes[c] = Math.max(colMaxes[c], grid[r][c]);
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s