Problem:
Returns the maximum number of consecutive subarrays and values in an array. Example: {31,-187, 26,-, 97,-93,-}, the maximum value is 59 + 26-53 + 58 + 97 =
Ideas:
When calculating the sum of consecutive subarrays between I and j, the maximum value is certainly obtained, but the time complexity is O (n ^ 2). We hope to find a linear time algorithm.
We noticed that,If all values in the array are positive, the largest and all values must be added together. If there is a negative number in the array and a negative number is added, the sum of the values of the subarray is less than 0, then the maximum and sub-arrays must not contain this negative number.Based on this, the following code is provided:
// Calculate the maximum and # include <stdio. h> int getmaxvalue (INT data [], int length) {int max = 0, temp = 0; int I = 0; for (I = 0; I <length; I ++) {temp = temp + data [I]; If (temp <0) temp = 0; else {If (temp> MAX) max = temp ;}} return Max;} int main () {int data [] = {31,-, 26,-, 97,-93 }; int length = sizeof (data)/sizeof (INT); int max = getmaxvalue (data, length); printf ("% d", max );}
The time complexity is O (n)