Skip to content

Commit 9721e97

Browse files
committed
max-sum-rectangle
1 parent aa6bb12 commit 9721e97

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

dp/lb-57-maximum-sum-rectangle.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
int kdnae(vector<int>& arr) {
3+
int n = arr.size();
4+
int curr = 0;
5+
int mx = INT_MIN;
6+
for (auto x : arr) {
7+
curr += x;
8+
mx = max(mx, curr);
9+
if (curr < 0) curr = 0;
10+
}
11+
return mx;
12+
}
13+
int maximumSumRectangle(int R, int C, vector<vector<int>> M) {
14+
int maximum = INT_MIN;
15+
for (int k = 0; k < R; k++) {
16+
vector<int> row(C, 0);
17+
for (int i = k; i < R; i++) {
18+
for (int j = 0; j < C; j++) {
19+
row[j] += M[i][j];
20+
}
21+
int maximal = kdnae(row);
22+
maximum = max(maximum, maximal);
23+
}
24+
}
25+
return maximum;
26+
}
27+
// from 0th row to last row
28+
// from 1st row to lat row
29+
// from last row to last row
30+
// NOTE: add one row above other to make is 1D to apply kdane;
31+
// Each possible rectangle is formed; from 1x1 to nxn.

0 commit comments

Comments
 (0)