LeetCode 1878: Get Biggest Three Rhombus Sums in a Grid Solution
Master LeetCode problem 1878 (Get Biggest Three Rhombus Sums in a Grid), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1878. Get Biggest Three Rhombus Sums in a Grid
Problem Explanation
Explanation
To solve this problem, we can iterate through all possible rhombus shapes in the grid and calculate their sums. We can achieve this by fixing the center of the rhombus and varying the radius to form the rhombus shape. For each rhombus, we calculate its sum by summing the values of the border elements. We then store the unique rhombus sums in a set and finally return the top three distinct sums in descending order.
- Time complexity: O(mnmin(m,n)) where m is the number of rows and n is the number of columns in the grid
- Space complexity: O(m*n)
Solution Code
import java.util.*;
class Solution {
public int[] getBiggestThree(int[][] grid) {
int m = grid.length;
int n = grid[0].length;
Set<Integer> rhombusSums = new HashSet<>();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rhombusSums.add(grid[i][j]);
for (int r = 1; i + r < m && i - r >= 0 && j + 2 * r < n; r++) {
int sum = 0;
for (int k = 0; k < r; k++) {
sum += grid[i - k][j + k] + grid[i + k][j + k] + grid[i - k][j + 2 * r - k] + grid[i + k][j + 2 * r - k];
}
rhombusSums.add(sum);
}
}
}
List<Integer> uniqueSums = new ArrayList<>(rhombusSums);
Collections.sort(uniqueSums, Collections.reverseOrder());
return uniqueSums.stream().limit(3).mapToInt(Integer::intValue).toArray();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1878 (Get Biggest Three Rhombus Sums in a Grid)?
This page provides optimized solutions for LeetCode problem 1878 (Get Biggest Three Rhombus Sums in a Grid) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1878 (Get Biggest Three Rhombus Sums in a Grid)?
The time complexity for LeetCode 1878 (Get Biggest Three Rhombus Sums in a Grid) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1878 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1878 in Java, C++, or Python.