C + + Learning (1): Maximum sub-segments and (multiple solutions)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.