Max Increase to Keep City Skyline

MediumMatrixgreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A city is laid out as an n x n grid, and grid[r][c] is the height of the building on block (r, c). Looking at the city from the left or right, you see the tallest building in each row; looking from the top or bottom, you see the tallest building in each column. These silhouettes form the city's skylines. You may raise the height of any buildings by any non-negative amounts, as long as the skyline seen from all four directions stays exactly the same. Return the **maximum total** amount by which the building heights can be increased.

Examples

Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]]
Output: 35
Row maxima are `[8,7,9,3]` and column maxima are `[9,4,8,7]`. Raising each building to `min(rowMax, colMax)` adds 35 in total.
Input: grid = [[0,0,0],[0,0,0],[0,0,0]]
Output: 0
Every row and column maximum is 0, so nothing can grow.

Constraints

  • `n == grid.length == grid[r].length`
  • `2 <= n <= 50`
  • `0 <= grid[r][c] <= 100`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems