算法分析之最小子段求和
#include <iostream> using namespace std; int MinSubSum(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,-19,13,-20,-1}; cout<<"最小字段和:"<<MinSubSum(5,a,besti,bestj)<<endl; cout<<"起始位置:"<<besti<<endl; cout<<"结束位置:"<<bestj<<endl; }