Problem description:
Given an integer array a [0 ~ N], calculate the child array of array a to make its element sum the largest.
Problem Analysis:
Method 1: You can use a common method to enumerate all sub-arrays, and then obtain the largest sub-array and the time complexity is O (n * n ).
Method 2: The Problem description meets the requirements of the optimal substructure for dynamic planning.
Set B [I] to end with a [I]
The maximum sub-segment and of the sub-array, that is:
B [I] = max {sum (A [J ~ K])}, where 0 <= j <= I, j <= k <= I.
Therefore, for Array a [0 ~ The maximum field of N] Is max {B [I]}, where 0 <= I <n.
When calculating B [I], you can consider the following three situations:
1, B [I] = B [I-1] + A [I], when B [I-1]> 0, then B [I] contains a [I].
2, B [I] = A [I], when B [I-1] <= 0, at this time a [I] again as the starting point of B [I.
3. B [I] does not contain a [I]. In this case, the results are calculated before B [I] and saved in B [0 ~ In I-1. The final calculation of max {B [I]} is considered.
B [I] = max {B [I-1] + A [I], a [I]}.
Array a [0 ~ N] Is max {B [I]}.
The array B [I] can be omitted during implementation. The implementation is as follows:
1 # include <iostream> <br/> 2 using namespace STD; <br/> 3 # define N 10 <br/> 4 int max_sub_array (Int & S, Int & E, int * A) <br/> 5 {<br/> 6 int I = 0; <br/> 7 Int J = 0; <br/> 8 int B, start, end; <br/> 9 int sum = 0; <br/> 10 sum = B = A [0]; <br/> 11 S = E = Start = END = 0; // s and E are the entire array a [0 ~ N. Start and end are arrays A [0 ~ I. <Br/> 12 for (I = 1; I <n; I ++) <br/> 13 {<br/> 14 if (B> 0) <br/> 15 {<br/> 16 B = B + A [I]; <br/> 17 end = I; <br/> 18} <br/> 19 else <br/> 20 {<br/> 21 B = A [I]; <br/> 22 start = END = I; <br/> 23} <br/> 24 if (sum <B) <br/> 25 {<br/> 26 sum = B; <br/> 27 s = start; <br/> 28 E = end; <br/> 29} <br/> 30} <br/> 31 return sum; <br/> 32} <br/> 33 int main () <br/> 34 {<br/> 35 int A [n] = {31,-, 26,-, 97,-93 }; <br/> 36 int start, end; <br/> 37 int sum = max_sub_array (START, end, ); <br/> 38 cout <sum <"" <start <"" <End <Endl; <br/> 39}