Ctrl K

Three Heaviest Diamonds

Medium
You are given an m × n table grid of positive numbers. A diamond is a square rotated by 45° whose four corners sit at cell centres, entirely inside the table. The sum of a diamond is the sum of the numbers in the cells along its outline (cells inside it do not count). A single cell is also a diamond, of size zero, and its sum is the cell's number. For example, the diamond with its top corner at (0, 1) goes through cells (0, 1), (1, 2), (2, 1) and (1, 0). Return the three largest **distinct** diamond sums in descending order. If there are fewer than three distinct sums, return all of them.
Example 1
grid=[[1, 2, 3], [4, 5, 6], [7, 8, 1]] → [20, 8, 7]

There is one diamond of nonzero size, around the centre: 2 + 6 + 8 + 4 = 20. The rest are single cells, and the largest of those are 8 and 7.

Example 2
grid=[[5, 5], [5, 5]] → [5]

Only single cells fit, and every sum is 5, so there is just one distinct value.

Example 3
grid=[[2, 9, 1, 4], [6, 3, 7, 2], [1, 8, 5, 3]] → [30, 11, 9]

The diamond topped by 9: 9 + 7 + 8 + 6 = 30. The one topped by 1: 1 + 2 + 5 + 3 = 11. The third value is the single cell 9.

Constraints
  • 1 ≤ m, n ≤ 50
  • 1 ≤ grid[i][j] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsK-th Largest Corner XOR MediumStudios for Recording Sessions MediumK-th Smallest in a Sorted Grid MediumNearest Points to the Base MediumShuttle Seat Plan Medium
loading Python…
Input
grid=[[1, 2, 3], [4, 5, 6], [7, 8, 1]]
Expected
[20, 8, 7]

Run checks the first 3 tests in your browser. Submit checks all 115 tests on the server, hidden ones included.