Given an integer array of length n, the maximum value of the number of two sub-arrays that do not overlap is obtained.
such as A[6]={1, 2,-4, 3, 2,-5}. When the sub-arrays are taken as {1,2}{3, 2}, two sub-arrays and the maximum, is 3+5=8.
This topic is the maximum and (that is, the maximum continuous and) deformation of the array's sub-array (the program that solves the largest and the Subarray is appended).
One method is to divide the array into two parts ([0~i] and [i+1~len-1]), respectively, to find the maximum continuity and addition of two parts, and then select the largest. The complexity of Time is O (n*n). This method is computationally redundant when solving the maximum continuity and needs to be optimized.
The second method applies two independent arrays, using sum1[i] to record the maximum contiguous and continuous of the array [0~i], and Sum2[i] records the maximum continuous and of the array [I, len-1]. Then Max (sum1[i]+sum2[i+1]) for every 0<=i<len-1 is the maximum value to be asked. Time complexity O (N). The code is as follows:
BOOLMax2sum (int* Arr,intLenint&max) { if(arr = = NULL | | Len <=1) return false; //Sum1[i], maximum continuous and from 0 to I intSum1[len]; //Sum2[i], maximum continuous and from I to len-1 intSum2[len]; intsum = arr[0]; sum1[0] =sum; for(inti =1; I < Len-1; i++) { if(Sum <=0) Sum=Arr[i]; Elsesum+=Arr[i]; if(sum1[i-1] <sum) sum1[i]=sum; ElseSum1[i]= sum1[i-1]; } Sum= arr[len-1]; Sum2[len-1] =sum; for(inti = len-2; i >0; i--) { if(Sum <=0) Sum=Arr[i]; Elsesum+=Arr[i]; if(sum2[i+1] <sum) sum2[i]=sum; ElseSum2[i]= sum2[i+1]; } intmax = sum1[0] + sum2[1]; for(inti =1; I < Len-1; i++) { if(Max < sum1[i] + sum2[i+1]) Max= Sum1[i] + sum2[i+1]; } returnMax;}
The code for solving a single sub-array and maximum value is as follows:
BOOLMaxsum (int* Arr,intLenint&max) { if(arr = = NULL | | Len <=0) return false; intsum = arr[0]; intMax =sum; for(inti =1; i < Len; i++) { if(Sum <=0) Sum=Arr[i]; Elsesum+=Arr[i]; if(Sum >max) Max=sum; } return true;}
The maximum and large of two sub-arrays that do not overlap in a one-dimensional array