-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmax_sum_sub_seq.cpp
More file actions
42 lines (40 loc) · 859 Bytes
/
max_sum_sub_seq.cpp
File metadata and controls
42 lines (40 loc) · 859 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
// 最大子序列
int maxSubSum(const vector<int> & arr,int &begin,int &end){
int maxSum=0;
int currSum=0;
int newbegin=0;
for(int i=0;i<arr.size();++i){
currSum+=arr[i];
if(currSum>maxSum){
maxSum=currSum;
begin=newbegin;
end=i;
}
if(currSum<0){
currSum=0;
newbegin=i+1;
}
}
return maxSum;
}
int main(){
int len;
cout<<"Input array length"<<endl;
cin>>len;
cout<<"Input an integer vector"<<endl;
vector<int> arr;
int a;
for(int i=0;i<len;++i){
cin>>a;
arr.push_back(a);
}
int begin,end;
cout<<maxSubSum(arr,begin,end)<<endl;
for(int i=begin;i<=end;++i)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}