Title: Enter an array of integers with positive and negative numbers in the array. One or more consecutive integers in an array make up a sub-array. The maximum value for the and of all sub-arrays. The required time is O (n).
To see this topic, the first thing we think of is to find out that all successive sub-arrays of the integer array and the array of length n has n (n+2)/2 sub-arrays, so it is required that these contiguous sub-arrays and the fastest also need O (n^2) time complexity. However, the time complexity of the O (n) required by the topic does not solve the problem.
using dynamic planning methodsThe idea of disintegration:
If you use the function f (i) to denote the maximum and the number of sub-arrays ending with the first digit, then we need to find Max (F[0...N]). We can give the following recursive formula to ask F (i)
The meaning of this formula:
- When the i-1 number is the end of all the numbers in the sub-array and F (i-1) is less than 0 o'clock, if the number of the negative and I add, the result is not the number of I itself is smaller, so in this case the largest sub-array and is the number I itself.
- If the sum of all the numbers in the subarray ending with the number (I-1) is greater than 0, the sum of all the numbers in the sub-array ending with the number of I is summed up with the number of i-1.
Code Implementation
//Use dynamic programming to find the largest contiguous subarray andint FindGreatestSumOfSubArray2 (int arry[],int Len,IntC[]) {c[0]=arry[0];IntStart,end;int temp=0;int maxgreatsum=-100;Forint i=1;i<len;i++) {if (c[i-1]<=0) {c[i]=Arry[i]; temp=I }Elsec[i]=arry[i]+c[i-1];if (c[i]>Maxgreatsum) {maxgreatsum=C[i]; start=temp; End=i;}} // output C[I] for (int i=0;i<len;i++) Cout<<c[i]<< "" endl; Cout<< " " <<start<< "--" <<end< <ENDL; return Maxgreatsum;}
In fact, the above two methods are very similar to the implementation, but the idea of disintegration is different. We usually use recursion to analyze the problem of dynamic programming, but eventually we will write the code based on the loop. An array created in the dynamic planning method c[] is used to store intermediate results, and only one temporary variable currsum is required in the first method.
Maximum sub-array and