已知一个整数的序列1,-2,3,10,-4,7,2,-5,求其最大子串的值,以及最大子串、
#include<iostream>
using namespace std;
int getSum(int *f,int n);
int main(){
int array[8]={1,-2,3,10,-4,7,2,-5};
int max = 0;
max = getSum(array,8);
cout<<max;
return 0;
}
int getSum(int *a,int n){
int sum = 0; //记录当前的sum值
int maxSum = 0; //记录最大的sum值
int start=0,end=0; //记录子串开始与结束位置
for(int i = 0;i<n;i++){
sum += a[i];
if(sum <0){
sum = 0;
start = i+1;
}
if(sum >0&&sum>maxSum){
maxSum = sum;
end = i;
}
if(i==n-1&&maxSum==0){
maxSum = a[0];
for(int j = 1;j<n;j++){
if(a[j]>a[0])
maxSum = a[j];
}
}
}
for(int i = start;i<=end;i++){
cout<<a[i]<< " ";
}
cout<<endl;
return maxSum;
}