#1878
Get Biggest Three Rhombus Sums in a Grid
MediumArrayMathSortingHeap (Priority Queue)MatrixPrefix SumPrefix SumSet for distinct values
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(m * n * min(m, n)) | O(m * n * min(m, n)) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n * min(m, n))Space O(m * n)
The optimal solution leverages prefix sums to efficiently calculate rhombus sums without recalculating overlapping areas. This reduces redundant calculations and speeds up the process significantly.
⚙️
Algorithm
3 steps- 1Step 1: Create a prefix sum array to store cumulative sums of the grid.
- 2Step 2: For each cell, calculate the rhombus sums using the prefix sums for all possible sizes.
- 3Step 3: Use a max-heap to keep track of the largest three distinct rhombus sums.
solution.py15 lines
1def getBiggestThree(grid):
2 m, n = len(grid), len(grid[0])
3 prefix_sum = [[0] * (n + 1) for _ in range(m + 1)]
4 for i in range(1, m + 1):
5 for j in range(1, n + 1):
6 prefix_sum[i][j] = grid[i - 1][j - 1] + prefix_sum[i - 1][j] + prefix_sum[i][j - 1] - prefix_sum[i - 1][j - 1]
7 rhombus_sums = set()
8 for i in range(m):
9 for j in range(n):
10 for size in range(min(i, j, m - i - 1, n - j - 1) + 1):
11 rhombus_sum = 0
12 for k in range(-size, size + 1):
13 rhombus_sum += (prefix_sum[i + k + 1][j + size + 1] - prefix_sum[i + k + 1][j - (size - abs(k))] - prefix_sum[i + k][j + 1] + prefix_sum[i + k][j - (size - abs(k))])
14 rhombus_sums.add(rhombus_sum)
15 return sorted(rhombus_sums, reverse=True)[:3]ℹ
Complexity note: The complexity is similar to the brute force approach, but we gain efficiency in calculating rhombus sums through the use of prefix sums, reducing redundant calculations.
- 1Understanding how to calculate rhombus sums is crucial for solving this problem.
- 2Using prefix sums can significantly reduce the number of calculations needed for overlapping areas.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.