Leetcode 1878: Get Biggest Three Rhombus Sums in a Grid

grid47
grid47
Exploring patterns and algorithms
May 3, 2024 6 min read

You are given an m x n matrix grid. A rhombus sum refers to the sum of the elements that form the border of a rhombus shape. The rhombus should be viewed as a square rotated 45 degrees, with each of its corners centered on a grid cell. Compute the biggest three distinct rhombus sums in the grid and return them in descending order. If there are fewer than three distinct sums, return all of them.
Problem
Approach
Steps
Complexity
Input: You are given a 2D matrix `grid` of integers.
Example: For grid = [[5,1,3],[4,2,6],[7,8,9]].
Constraints:
• 1 <= m, n <= 50
• 1 <= grid[i][j] <= 10^5
Output: Return the biggest three distinct rhombus sums in descending order. If fewer than three distinct sums exist, return all of them.
Example: For grid = [[5,1,3],[4,2,6],[7,8,9]], the output is [25, 17, 12].
Constraints:
• The output should be an array of integers representing the biggest three distinct rhombus sums.
Goal: To find the rhombus sums, we need to iterate through all possible centers in the grid and calculate the sum of elements that form the rhombus for each center.
Steps:
• Iterate over each cell in the grid to treat it as a potential center of a rhombus.
• For each center, compute the sum of all grid elements that form the rhombus border.
• Store these sums in a set to ensure distinct values.
• Sort the set and return the top three distinct sums.
Goal: Ensure that the grid contains positive integers and is within the allowed size.
Steps:
• 1 <= m, n <= 50
• 1 <= grid[i][j] <= 10^5
Assumptions:
• The grid is at least 1x1 in size.
• All grid elements are positive integers.
Input: For grid = [[5,1,3],[4,2,6],[7,8,9]].
Explanation: The rhombus sums for the three biggest distinct rhombuses are: 25, 17, and 12.

Input: For grid = [[7, 7, 7]].
Explanation: Since all rhombus sums are the same, the output is [7].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus