-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmaximum_sum_rectangle.cpp
74 lines (60 loc) · 1.26 KB
/
maximum_sum_rectangle.cpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
Author: Andres Zibula
Github: https://github.com/andres-zibula/geekforgeeks-problems-solved
Problem link: http://practice.geeksforgeeks.org/problems/maximum-sum-rectangle/0
Description: Given a 2D array, find the maximum sum subarray in it.
*/
#include <iostream>
using namespace std;
int rect_sum(int **array, int x_from, int y_from, int x_to, int y_to)
{
int sum = 0;
for (int i = y_from; i <= y_to; ++i)
{
for (int j = x_from; j <= x_to; ++j)
{
sum += array[i][j];
}
}
return sum;
}
int main()
{
int T, R, C;
cin >> T;
for (int i = 0; i < T; ++i)
{
cin >> R;
cin >> C;
int **array = new int *[R];
for (int i = 0; i < R; ++i)
{
array[i] = new int[C];
for (int j = 0; j < C; ++j)
{
cin >> array[i][j];
}
}
int max_sum = array[0][0];
for (int i = 0; i < R; ++i)
{
for (int j = 0; j < C; ++j)
{
for (int k = i; k < R; ++k)
{
for (int l = j; l < C; ++l)
{
int sum = rect_sum(array, j, i, l, k);
if (max_sum < sum)
max_sum = sum;
}
}
}
}
cout << max_sum << endl;
for (int i = 0; i < R; ++i)
delete[] array[i];
delete[] array;
}
return 0;
}