{x}
blog image

Get Biggest Three Rhombus Sums in a Grid

You are given an m x n integer matrix grid​​​.

A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in grid​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum:

Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner.

Return the biggest three distinct rhombus sums in the grid in descending order. If there are less than three distinct values, return all of them.

 

Example 1:

Input: grid = [[3,4,5,1,3],[3,3,4,2,3],[20,30,200,40,10],[1,5,5,4,1],[4,3,2,2,5]]
Output: [228,216,211]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 20 + 3 + 200 + 5 = 228
- Red: 200 + 2 + 10 + 4 = 216
- Green: 5 + 200 + 4 + 2 = 211

Example 2:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]]
Output: [20,9,8]
Explanation: The rhombus shapes for the three biggest distinct rhombus sums are depicted above.
- Blue: 4 + 2 + 6 + 8 = 20
- Red: 9 (area 0 rhombus in the bottom right corner)
- Green: 8 (area 0 rhombus in the bottom middle)

Example 3:

Input: grid = [[7,7,7]]
Output: [7]
Explanation: All three possible rhombus sums are the same, so return [7].

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 50
  • 1 <= grid[i][j] <= 105

Problem: 1878. Get Biggest Three Rhombus Sums in a Grid

This problem asks to find the three largest distinct sums of elements forming the borders of rhombus shapes within a given grid. A rhombus is defined as a square rotated 45 degrees, with its corners centered on grid cells.

Approach: Enumeration and Optimization

The most straightforward approach involves iterating through all possible rhombus centers and sizes within the grid. For each rhombus, we calculate its sum and store it in a data structure that efficiently manages the largest three distinct sums. However, brute-force calculation of each rhombus sum is inefficient. We can significantly improve performance using prefix sums.

1. Prefix Sum Optimization:

To avoid repeatedly summing elements for each rhombus, we precompute two prefix sum matrices:

  • s1[i][j]: The sum of elements along the upper-left diagonal ending at (i, j).
  • s2[i][j]: The sum of elements along the upper-right diagonal ending at (i, j).

With these matrices, the rhombus sum can be calculated efficiently using subtractions of prefix sums.

2. Rhombus Sum Calculation:

The sum of a rhombus with center (i, j) and side length k is calculated as:

sum = s1[i + k][j] - s1[i][j - k] + s1[i][j + k] - s1[i - k][j] +
      s2[i][j - k] - s2[i - k][j] + s2[i + k][j] - s2[i][j + k] -
      grid[i + k - 1][j - 1] + grid[i - k - 1][j - 1] 

The last two terms adjust for potential double-counting of elements in the diagonals.

3. Efficiently Tracking the Top Three:

To keep track of the three largest distinct sums efficiently, we use an ordered set (or a similar data structure like a priority queue). This automatically maintains the elements in sorted order, and we can easily add new sums and remove smaller sums when the set size exceeds three.

Time and Space Complexity Analysis

  • Time Complexity: O(mnmin(m, n)) - We iterate through all possible rhombus centers (mn) and for each center we iterate up to min(m, n) times for different rhombus sizes. The prefix sum calculation is O(mn).

  • Space Complexity: O(m*n) - We need to store the two prefix sum matrices. The ordered set has a maximum size of 3, which is constant space.

Code Implementation (Python)

import heapq
 
class Solution:
    def getBiggestThree(self, grid: List[List[int]]) -> List[int]:
        m, n = len(grid), len(grid[0])
        
        #Precompute prefix sums
        s1 = [[0]*(n+2) for _ in range(m+1)]
        s2 = [[0]*(n+2) for _ in range(m+1)]
        for i in range(1, m+1):
            for j in range(1, n+1):
                s1[i][j] = s1[i-1][j-1] + grid[i-1][j-1]
                s2[i][j] = s2[i-1][j+1] + grid[i-1][j-1]
        
        # Find biggest three distinct rhombus sums using a max-heap
        top_three = []
        seen = set()
        for i in range(1, m+1):
            for j in range(1, n+1):
                l = min(i-1, m-i, j-1, n-j)
                
                # Add the single element rhombus sum
                if grid[i-1][j-1] not in seen:
                  heapq.heappush(top_three, -grid[i-1][j-1])
                  seen.add(grid[i-1][j-1])
 
                for k in range(1, l+1):
                    rhombus_sum = s1[i+k][j] - s1[i][j-k] + s1[i][j+k] - s1[i-k][j] + \
                                  s2[i][j-k] - s2[i-k][j] + s2[i+k][j] - s2[i][j+k] - \
                                  grid[i+k-1][j-1] + grid[i-k-1][j-1]
                                  
                    if rhombus_sum not in seen:
                        heapq.heappush(top_three, -rhombus_sum)
                        seen.add(rhombus_sum)
                    if len(top_three) > 3:
                        heapq.heappop(top_three)
 
        return sorted([-x for x in top_three])

Other languages like Java, C++, and Javascript can be implemented similarly, using appropriate data structures for prefix sums and managing the top three distinct sums (e.g., TreeSet in Java, std::set in C++, or a min-heap in Javascript). The core algorithm remains the same.