# Dynamic programming -- Maximum subarray and

Problem Description:

Given a n integer array a[0~n], find the sub array of array a, and make its element sum the maximum.

Problem analysis:

Method 1: enumerate all subarrays with common methods, and then find the largest sum of subarrays with time complexity of O(n*n).

Method 2: the problem description meets the requirements of optimal substructure of dynamic programming.

Let b[i] denote the maximum sum of sub segments of the sub array ending with a[i], that is:

b[i]=max{sum(a[j~k])}, where 0 < = J < = I, J < = k < = I.

Therefore, the maximum field sum of array a[0~n] is max{b[i]}, where 0 < = I < n.

When calculating b[i], the following three situations can be considered:

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, a[i] is taken as the starting point of b[i].

3. When b[i] does not contain a[i], the result has been calculated before b[i] is calculated and saved in b[0~i-1]. Finally, the max{b[i]} will be calculated.

b[i] = max{ b[i-1]+a[i]，a[i]}.

The array a[0~n] is max{b[i]}.

In implementation, array b[i] can be omitted. The implementation is as follows:

1. 1 #include <iostream>
2.  2 using namespace std;
3.  3 #define N 10
4.  4 int max_sub_array(int &s,int &e,int * a)
5.  5 {
6.  6         int i=0;
7.  7         int j =0;
8.  8         int b,start,end;
9.  9         int sum = 0;
10. 10         sum = b = a[0];
11. 11         s = e = start = end = 0;//s and e are the starting and ending positions of the largest sub segments of the whole array a[0~n]. start and end are the starting and ending positions of array a[0~i].
12. 12         for(i = 1;i<N;i++)
13. 13         {
14. 14                 if(b>0)
15. 15                 {
16. 16                         b = b + a[i];
17. 17                         end = i;
18. 18                 }
19. 19                 else
20. 20                 {
21. 21                         b = a[i];
22. 22                         start = end = i;
23. 23                 }
24. 24                 if(sum<b)
25. 25                 {
26. 26                         sum = b;
27. 27                         s = start;
28. 28                         e = end;
29. 29                 }
30. 30         }
31. 31         return sum;
32. 32 }
33. 33 int main()
34. 34 {
35. 35         int a[N]={31,-41,59,26,-53,58,97,-93,-23,84};
36. 36         int start,end;
37. 37         int sum = max_sub_array(start,end,a);
38. 38         cout << sum << "  "<<start<< " "<<end<< endl;
39. 39 }

Tags: Programming

Posted on Sun, 03 May 2020 09:17:04 -0400 by sepodati