1878. Get Biggest Three Rhombus Sums in a Grid
Approach
For each cell try all rhombus sizes; compute border sums with diagonal prefix sums; track top 3.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
// Approach: For each cell try all rhombus sizes; compute border sums with diagonal prefix sums; track top 3.
// Time: O(mn * min(m,n)) Space: O(mn)
public class Solution
{
public int[] GetBiggestThree(int[][] grid)
{
int m = grid.Length;
int n = grid[0].Length;
SortedSet<int> sums = new SortedSet<int>();
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz)
{
int sum = sz == 0 ? grid[i][j] : GetSum(grid, i, j, sz);
sums.Add(sum);
if (sums.Count > 3)
sums.Remove(sums.Min);
}
}
}
return sums.Reverse().ToArray();
}
// Returns the sum of the rhombus, where the top grid is (i, j) and the edge size is `sz`.
private int GetSum(int[][] grid, int i, int j, int sz)
{
int x = i;
int y = j;
int sum = 0;
// Go left down.
for (int k = 0; k < sz; ++k)
sum += grid[--x][++y];
// Go right down.
for (int k = 0; k < sz; ++k)
sum += grid[++x][++y];
// Go right up.
for (int k = 0; k < sz; ++k)
sum += grid[++x][--y];
// Go left up.
for (int k = 0; k < sz; ++k)
sum += grid[--x][--y];
return sum;
}
}