here are two ways:
first,we could set a variable "temp" which equals zero,and we could get the element of the array one by one.Every time we get a number,we must judge,if temp is less than or equal to zero.If temp<=0, it means that the sum of the previous sequence could not give any contribution to the all possible remaining sequence,so we set it to current value we visit.Or we add current element to the variable-----temp.And we compare temp with the variable res which is used to store the result.If temp is greater than res,we should assign the value of temp to res.
Apart from the previous solutions,we could do it another way:As for any array elem[1......j],when we read the new element elem[j+1],we could find that the maximum sum could only be the maximum sum of subsequence of elem[1......j] or the sum of elem[i......j+1],so we use temp to store the sum of sequence we have travesed,and we also use the variable "before" to represent the previous minimum sum of sequence.And we use (temp-before) to compare with res,and update res if (temp-before>res),and we also upate the variable "before" if (temp<before).We initialize "before" to 0(it is very important)
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<xfunctional>
using namespace std;
int find_maxsum1(vector<int>& elem){
int sum = INT_MIN;
int temp = 0;
for (int i = 0; i < elem.size(); i++){
if (temp <= 0) temp = elem[i];
else temp += elem[i];
if (temp > sum) sum = temp;
}
return sum;
}
int find_maxsum2(vector<int>& elem){
int before = 0;
int max_sum = INT_MIN;
int temp = 0;
for (int i = 0; i < elem.size(); i++){
temp += elem[i];
if (temp - before > max_sum){
max_sum = temp - before;
}
if (before > temp){
before = temp;
}
}
return max_sum;
}
int main(){
int n;
cout << "Input the amount of the element:";
cin >> n;
vector<int> elem(n,0);
for (int i = 0; i < n; i++) cin >> elem[i];
int res1 = find_maxsum1(elem);
int res2 = find_maxsum2(elem);
cout << "The result: " << res1 << endl;
cout << "The result: " << res2 << endl;
system("pause");
return 0;
}