All problems

Problem 997

Max Increase to Keep City Skyline

Medium · 20 pts · Matrix, Greedy

Problem

An N × N grid gives the heights of buildings in a city. The skyline seen from the north or south is the tallest building in each column, and from the east or west the tallest in each row. You may increase the height of any building by any amount without changing the skyline from any direction. Find the largest total increase. Building (i, j) can grow up to min(tallest in row i, tallest in column j).

Input

The first line contains N. Each of the next N lines contains N integers.

Output

Print the maximum total increase.

Constraints

2 <= N <= 50; 0 <= height <= 100

Example input

4
3 0 8 4
2 4 5 7
9 2 6 3
0 3 1 0

Example output

35

Explanation

For 3 0 8 4 / 2 4 5 7 / 9 2 6 3 / 0 3 1 0, raising every building to the smaller of its row and column maximum adds 35 in total without changing any skyline.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Largest Local Values in a Matrix Next: Spiral Matrix III