Title: The largest contiguous subarray of non-recursive arrays (contiguous and maximal subarray) in linear time.
Idea: Set the maximum subarray to Max, the start and end positions are S, E, the and of the sub-arrays being scanned are add, the start and end positions are I, J. The initial value of Max is-∞.
1. If the value of the array is all negative, the maximum value is returned.
2. Scan the array elements individually, updating the values of add, I, J.
A. If the value of add is positive, then the value for Max, S, and E is updated to add, I, J, if it is greater than Max's value.
B. If the value of add is negative, then the number of the paragraph from I to J can only reduce the and of the sub-array, to discard, add value clear 0 and the next element to start the calculation again, update the values of I, J.
#include <iostream>using namespacestd;inta[ -];intMain () {intsize; CIN>>size; BOOLneg_flag=true;//The maximum value is returned when all are negative. intneg_max=-1e10; for(intI=0; i<size;i++) {//enter and determine if all is negative. Cin>>A[i]; if(a[i]>=0) {Neg_flag=false; } if(a[i]>Neg_max) {Neg_max=A[i]; } } if(neg_flag==true) {cout<<"Max is"<<neg_max<<"start from"<<neg_max<<" to"<<neg_max<<Endl; return 0; } intMax=-1e10;//Max and. ints=-1;//The maximum sub-array start point. inte=-1;//The maximum sub-array end point. intAdd=0;//scans sub-arrays and. intI=0;//scans the start of a sub-array. intj=0;//scans the end of the sub-array. while(j<size) {Add+=A[j]; if(add>=0){ if(add>=max) {Max=add; S=i; E=J; } ++J; } Else{ ++J; I=J; if(j<size) {Add=0; } }} cout<<"Max is"<<max<<"start from"<<A[s]<<" to"<<A[e]<<Endl;}
[Introduction to Algorithms] Exercise 4.1-5 maximal continuous subarray problem