Maximum sub-array and

Source: Internet
Author: User

Maximum sub-arrays and problems:

Given an array of a[0,1...,n-1], a continuous subarray of a is obtained, making the Subarray and the largest.

Example: array: 1,-2,3,10,-4,7,2,-5

Subarray: 3,10,-4,7,2; this subarray is 18.

Program implementation:

1 /***************************************2 FileName MaxSumSubArray.cpp3 Author:godfrey4 CREATEDTIME:2016/5/45 ****************************************/6#include <iostream>7#include <cstring>8#include <vector>9#include <algorithm>Ten#include <stdio.h> One#include <stdlib.h> A  - using namespacestd; -  the intMaxsumsubarray (intAintSizeint& from,int&To ) { -     if( ! A | | Size <=0){//Error Detection -          from= -1; -to =-1; +         return 0; -     } +      from= to =0; A     intsum = a[0];//the and of the current substring at     intresult = SUM;//the optimal solution of the current sub-string -     intfromupdate; -      for(intI=1; i<size;i++){ -         if(Sum >0){ -Sum + =A[i]; -         } in         Else{ -sum =A[i]; toFromupdate = i;//Update sub-array starting point when sum<0 +         } -  the         if(Result < SUM) {//when the current optimal solution is updated, the starting point is updated *result =sum; $              from=fromupdate;Panax Notoginsengto =i; -         } the     } +     returnresult; A } the intMain () + { -     intA[] = {1,-2,3,Ten,-4,7,2,-5}; $     intStart,end; $     intresult = Maxsumsubarray (A,sizeof(a)/sizeof(int), start,end); -cout<<"The Maxsumsubarray:"; -cout<<result<<Endl; thecout<<"Start:"<<start<<"End:"<<end<<Endl; -cout<<"The Subarray is:"<<Endl;Wuyi      for(inti = start;i<=end;i++){ thecout<<a[i]<<" "; -     } Wucout<<Endl; -     return 0; About}

Operation Result:

Reprint please specify the source:

C + + Blog Park: godfrey_88

http://www.cnblogs.com/gaobaoru-articles/

Maximum sub-array and

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.