Problem: Given a sequence consisting of n number (possibly negative) a1,a2,a3,..., An, the maximum value of the sequence sub-segment is obtained.
The first solution: (The easiest method to consider, add all the sub-segments one by one, and then compare)
1#include <iostream>2 using namespacestd;3 intMaxsum (intNint*a,int&besti,int&Bestj)4 {5 intsum =0;6 for(intI=1; i<=n;i++)7 {8 intThissum =0;9 for(intj=i;j<=n;j++)Ten { OneThissum + =A[j]; A if(thissum>sum) - { -sum =thissum; theBesti =i; -BESTJ =J; - } - } + } - returnsum; + } A at intMain () - { - intCase =1; - intT//total number of groups -Cin>>T; - while(t>0) in { -t--; to intsum; + intN =9;//How many data are there in a group? -Cin>>N; the int* Array =New int[n+1]; * for(intI=1; i<=n;i++) $ {Panax NotoginsengCin>>Array[i]; - } the intBesti,bestj; +sum =maxsum (N,ARRAY,BESTI,BESTJ); Acout<<" Case"<<Case<<":"<<Endl; thecout<<sum<<" "<<besti<<" "<<bestj<<Endl; + - if(t>0) $ { $cout<<Endl; - } -case++; the } - return 0;Wuyi}
C + + Learning (1): Maximum sub-segments and (multiple solutions)