[LeetCode] Equal Sum Grid Partition I

3546. Equal Sum Grid Partition I

You are given an m x n matrix grid of positive integers. Your task is to determine if it is possible to make either one horizontal or one vertical cut on the grid such that:

  • Each of the two resulting sections formed by the cut is non-empty.
  • The sum of the elements in both sections is equal.

Return true if such a partition exists; otherwise return false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
bool canPartitionGrid(vector<vector<int>>& grid) {
long long n = grid.size(), m = grid[0].size(), sum = 0;
vector<long long> row(n), col(m);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
sum += grid[i][j];
row[i] += grid[i][j];
col[j] += grid[i][j];
}
}
auto check = [&](vector<long long>& pre) {
for(int i = 0; i < pre.size() - 1; i++) {
if(i) pre[i] += pre[i-1];
if(pre[i] * 2 == sum) return true;
if(pre[i] * 2 > sum) break;
}
return false;
};
return !(sum & 1) and (check(row) or check(col));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/05/11/PS/LeetCode/equal-sum-grid-partition-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.