The largest continuous sub-array and code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: enter an integer array with a positive or negative number in the array. One or more consecutive integers in the array form a subarray. Calculate the maximum value of the sum of all subarrays.
Save with a numberCurrent and, IfThe current sum is less than 0, Replace the new value. Otherwise, increment and save with a number.Temporary maximum value.
Code:
/** Main. CPP ** created on: June 29, 2014 * Author: Wang */# include <stdio. h> # include <limits. h> using namespace STD; int getgreatestsumofsubarray (int * pdata, int length) {If (pdata = NULL | length <= 0) return 0; int ncursum = 0, ngreatestsum =-int_max; For (INT I = 0; I <length; ++ I) {If (ncursum <= 0) ncursum = pdata [I]; else ncursum + = pdata [I]; If (ncursum> ngreatestsum) ngreatestsum = ncursum;} return ngreatestsum;} int main (void) {int data [] = {1, -2, 3, 10,-4, 7, 2,-5}; int result = getgreatestsumofsubarray (data, 8); printf ("result = % d \ n ", result); Return 0 ;}
Output:
result = 18