#807
Max Increase to Keep City Skyline
MediumArrayGreedyMatrixArrayGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
The optimal solution leverages the same principles as the brute force but calculates the maximum heights for rows and columns in a single pass. This reduces the number of iterations needed to compute the total increase.
⚙️
Algorithm
3 steps- 1Step 1: Initialize maxRow and maxCol arrays to store the maximum heights for each row and column.
- 2Step 2: Iterate through the grid once to fill maxRow and maxCol simultaneously.
- 3Step 3: Calculate the total increase in a single pass using the precomputed maxRow and maxCol.
solution.py13 lines
1def maxIncreaseKeepingSkyline(grid):
2 n = len(grid)
3 maxRow = [0] * n
4 maxCol = [0] * n
5 totalIncrease = 0
6 for r in range(n):
7 for c in range(n):
8 maxRow[r] = max(maxRow[r], grid[r][c])
9 maxCol[c] = max(maxCol[c], grid[r][c])
10 for r in range(n):
11 for c in range(n):
12 totalIncrease += min(maxRow[r], maxCol[c]) - grid[r][c]
13 return totalIncreaseℹ
Complexity note: The time complexity remains O(n²) due to iterating through the grid, but we optimize the process by combining the height calculations into fewer iterations. The space complexity is O(n) for storing max heights.
- 1The maximum height of each building is constrained by the maximum heights of its corresponding row and column.
- 2The skyline from each direction must remain unchanged, which means we can only increase heights up to the minimum of the maximum row and column heights.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.