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