Leetcode 807. Max Increase to Keep City Skyline
You are given a n x n
grid representing the height of buildings in a city. The heights of the buildings are represented by integers in the grid. The goal is to determine the maximum total sum that the height of the buildings can be increased without changing the city’s skyline from any viewpoint (north, south, east, or west).
Example:
Input: grid = [[3,0,8,4],
[2,4,5,7],
[9,2,6,3],
[0,3,1,0]]
Output: 35
Explanation: The skyline viewed from north and south is [9, 4, 8, 7]
, and the skyline viewed from east and west is [8, 7, 9, 3]
. The grid after increasing the height of the buildings without affecting the skyline is:
gridNew = [[8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3]]
The sum of the returned new grid is 35.
Let’s start by writing the code to solve this problem in C++.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {
int n = grid.size();
// Create two vectors to store the max heights of rows and columns
vector<int> rowMax(n, 0);
vector<int> colMax(n, 0);
// Compute the max heights for each row and column
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]);
}
}
// Calculate the maximum increase while maintaining the skyline
int totalIncrease = 0;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < n; ++j) {
totalIncrease += min(rowMax[i], colMax[j]) - grid[i][j];
}
}
return totalIncrease;
}
};
rowMax
and colMax
to identify the maximum height in each row and each column of the grid.The time complexity of this solution is (O(n^2) ), where ( n ) is the dimension of the grid. This is because we have to traverse all the elements of the grid twice:
rowMax
and colMax
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?