-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximum Subarray sum.cpp
61 lines (58 loc) · 1.17 KB
/
Maximum Subarray sum.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
#include <bits/stdc++.h>
using namespace std;
//Dynammic Programming Kadane's Algo O(n)
int kadane(vector<int> v){
int msum=v[0];
int lsum=v[0];
for(int i=1;i<v.size();i++){
lsum=max(lsum+v[i],v[i]);
if(msum<lsum)
msum=lsum;
}
return msum;
}
//BRUTE FORCE O(n^3)
int maxSubarraySum(vector<int> v){
int msum=INT_MIN;
for(int i=0;i<v.size();i++){
for(int j=i;j<v.size();j++){
int sum=0;
for(int k=i;k<=j;k++){
sum+=v[k];
}
if(sum>msum)
msum=sum;
}
}
return msum;
}
//BRUTE FORCE optimised O(n^2)
int optimisedSubarraysum(vector<int> v){
int msum=INT_MIN;
for(int i=0;i<v.size();i++){int sum=0;
for(int j=i;j<v.size();j++){
sum=sum+v[j];
if(sum>msum)
msum=sum;
}
}
return msum;
}
int main() {
int t;
cin>>t;
while(t--){
int k;
cin>>k;
vector<int> v;
while(k--){
int p;
cin>>p;
v.push_back(p);
}
cout<<maxSubarraySum(v)<<endl;
cout<<optimisedSubarraysum(v)<<endl;
cout<<kadane(v)<<endl;
}
return 0;
}