You are given an n x n
grid representing the heights of buildings in a city. The grid is sent as a list of lists. The height of the building at row i
and column j
is grid[i][j]
.
You are allowed to increase the height of any building, but keeping in mind the following constraints for each building:
You need to find the maximum total sum of the heights that the buildings can be increased.
Input:
grid = [
[3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0]
]
Output:
35
Explanation:
[
[8, 4, 8, 7],
[7, 4, 7, 7],
[9, 4, 8, 7],
[3, 3, 3, 3]
]
(8-3) + (4-0) + (8-8) + (7-4) +
(7-2) + (4-4) + (7-5) + (7-7) +
(9-9) + (4-2) + (8-6) + (7-3) +
(3-0) + (3-3) + (3-1) + (3-0) = 35
n x n
)?n
?max_row
).max_col
).def maxIncreaseKeepingSkyline(grid):
n = len(grid)
# Step 1: Calculate maximum heights of each row
max_row = [max(row) for row in grid]
# Step 2: Calculate maximum heights of each column
max_col = [max(grid[i][j] for i in range(n)) for j in range(n)]
total_increase = 0
# Step 3 and 4: Calculate the total increase
for i in range(n):
for j in range(n):
# Find the minimum of max_row and max_col values for the current cell
max_height = min(max_row[i], max_col[j])
total_increase += max_height - grid[i][j]
return total_increase
# Example usage
grid = [
[3, 0, 8, 4],
[2, 4, 5, 7],
[9, 2, 6, 3],
[0, 3, 1, 0]
]
print(maxIncreaseKeepingSkyline(grid)) # Output: 35
The time complexity of the solution is:
Thus, the overall time complexity is O(n^2).
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?