#include <iostream> using namespace std; int MaxSubSum(int n,int a[],int &besti,int &bestj){ int sum =0,b=0; int j; for(j=0;j<n;j++){ b+=a[j]; if(b<0){ b=0; besti=j+1;//一旦b<0,抛弃前面的结果,把j的下一个位置记录下来 bestj=j+1; } if(b>sum){ sum=b; bestj=j;//bestj跟着sum更新而更新 } } return sum; } int main(){ int besti,bestj; besti=bestj=0; int a[5]={-2,-1,3,2,-1}; cout<<"最大字段和:"<<MaxSubSum(5,a,besti,bestj)<<endl; cout<<"起始位置:"<<besti<<endl; cout<<"结束位置:"<<bestj<<endl; }