Question:
Enter an integer array, and the array contains positive and negative numbers.
One or more consecutive integers in the array form a sub-array. Each sub-array has a sum.
Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ).
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the maximum sub-array is 3, 10,-4, 7, 2,
Therefore, the output is the sum of 18 of the sub-array.
Find the state transition equation. dp [I] indicates the largest sum of subarrays containing I in the first I count. Either the number I is the largest, or he wants to be joined together with the largest child array containing the I-1 (that is, dp [I-1.
That is, dp [I] = max {arr [I], dp [I-1] + arr [I]};
The Code is as follows;
Copy codeThe Code is as follows: # include <stdio. h>
# Define max (a, B) (a)> (B )? (A) :( B)
Int res (int * arr, int len ){
// Learn a method to define the minimum number :)
Int max =-(1 <31 );
Int I;
For (I = 1; I <len; I ++ ){
Arr [I] = max (arr [I], arr [I-1] + arr [I]);
If (max <arr [I]) max = arr [I];
}
Return max;
}
Int main (){
Int arr [] = {1,-2, 3, 10,-4, 7, 2,-5 };
Printf ("% d \ n", res (arr, 8 ));
Return 0;
}