Topic:
Enter an integer array, the data element has a positive number and a negative number, the sum of the elements combined into a contiguous array of the largest array of children, requiring time complexity of O (n).
For example:
The input array is 1,-2, 3, 10,-4, 7, 2,-5, the largest and contiguous sub array is 3, 10,-4, 7, 2, and its maximum and 18.
Background:
At the beginning of the 2005, Zhejiang University Computer Department, the last one of the final program design questions, including Google in 2006 years, many well-known companies are considered as face questions.
Due to the topic in the network widely circulated, the subject has also successfully become the 2006 Programmer interview Questions Classic Classic.
Analysis:
If time complexity is not considered, we can enumerate all the sub arrays and find out their and. Unfortunately, because an array of length n has an O (N2) array (that is, n + n-1 + ... + 1=n (n+1)/2), and the time complexity of an array of length n is O (n). So the time of this idea is O (N3).
It is easy to understand that when we add a positive number, it increases; when we add a negative number, it is reduced. If the current sum is negative, then this and the next addition should be discarded and cleared again, otherwise the negative will decrease the sum of the following. Based on this idea, we can write the following code.
void maxsum (int array[], unsigned int len)
{
if (NULL = = Array | | | len <=0) {return
;
}
int cursum = 0, maxsum = 0;
int i = 0;
For (i=0 i<len; i++) {
cursum + = Array[i]; Add
if (Cursum < 0) { //current and less than 0, reset to 0
cursum = 0;
}
if (Cursum > Maxsum) {//current and greater than Max and, reset Max and
maxsum = cursum;
}
}
if (maxsum = = 0) { //maximum and still 0, indicating that all elements in the array are
negative
maxsum = array[0];
For (I=1 i<len; i++) {
if (Array[i] > Maxsum) {
maxsum = array[i];
}}} printf ("Maxsum:%d", maxsum);
}
To test an array:
int array[] = {1,-2, 3, -4, 7, 2,-
5}; 3, 10,-4, 7, 2 = 18
Run Result: