[LeetCode] Get Biggest Three Rhombus Sums in a Grid

1878. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public:
vector<int> getBiggestThree(vector<vector<int>>& grid) {
vector<int> res;

int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int sz = 1, sum = 0;
res.push_back(grid[i][j]);
bool brk = false;
while(!brk) {
int y = i, x = j;
for(int k = 0; k < sz and !brk; k++) {
sum += grid[y][x];
y += 1, x -= 1;
if(y < 0 or y >= n or x < 0 or x >= m) brk = true;
}

for(int k = 0; k < sz and !brk; k++) {
sum += grid[y][x];
y += 1, x += 1;
if(y < 0 or y >= n or x < 0 or x >= m) brk = true;
}

for(int k = 0; k < sz and !brk; k++) {
sum += grid[y][x];
y -= 1, x += 1;
if(y < 0 or y >= n or x < 0 or x >= m) brk = true;
}

for(int k = 0; k < sz and !brk; k++) {
sum += grid[y][x];
y -= 1, x -= 1;
if(y < 0 or y >= n or x < 0 or x >= m) brk = true;
}
if(!brk) {
res.push_back(sum);
sz++;
sum = 0;
}
}
}
}

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
res.push_back(grid[i][j]);
}
}

sort(begin(res), end(res));
res.erase(unique(begin(res), end(res)), end(res));
reverse(begin(res),end(res));
res.resize(3);
while(res.back() == 0) res.pop_back();
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/14/PS/LeetCode/get-biggest-three-rhombus-sums-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.