-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMax Sum in 2D array.cpp
94 lines (68 loc) · 2.07 KB
/
Max Sum in 2D array.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<bits/stdc++.h>
using namespace std;
// function to find max sum subarray in 1D matrix using kadane's algorithm in O(n).
vector<int> max_sum_subarray(vector<int> a)
{
vector<int> res(3,-1);
int curr_max = a[0],max=a[0],start_index=0,end_index=0,mstart=0,mend=0;
for(int i=1;i<a.size();i++)
{
if(curr_max<0)
{
start_index = i;
end_index = i;
curr_max = a[i];
}
else
{
curr_max += a[i];
end_index = i;
}
if(curr_max>max)
{
mstart = start_index;
mend = end_index;
max = curr_max;
}
}
res[0] = max;
res[1] = mstart;
res[2] = mend;
return res;
}
int main()
{
vector<vector<int> > a = {
{6,-5,-7,4,-4},
{-9,3,-6,5,2},
{-10,4,7,-6,3},
{-8,9,-3,3,-7}
};
int n = a.size(); //rows
int m = a[0].size(); //cols
int left_index=0,right_index=0,up_index=0,down_index=0,max_sum=a[0][0];
vector<int> res(3); // stores the result from max_sum_subarray function (max_sum,start_index,end_index)
for(int i=0;i<m;i++)
{
vector<int> row_sum(n,0);
for(int j=i;j<m;j++)
{
for(int k=0;k<n;k++)
{
row_sum[k] += a[k][j];
}
res = max_sum_subarray(row_sum);
if(res[0]>max_sum)
{
max_sum = res[0];
left_index = i;
right_index = j;
up_index = res[1];
down_index = res[2];
}
}
}
cout << "top left ( " << up_index << " , " << left_index << " )\n";
cout << "bottom right ( " << down_index << " , " << right_index << " )\n";
cout << "Sum: " << max_sum;
}