Title Description
Given an array a[0,..., n-1], find its maximum subarray (length >=1) and
Enter a description
First line an integer n (1<=n<=5000), and then enter n integers (each integer range [-5000, 5000])
Output description
Outputs an integer representing the maximum number of sub-arrays and
Sample input
51-1 1 1-1
Sample output
2
Of course there are search or enumeration and so on, O (n) algorithm can be used DP.
Set Sum[i] is the contiguous subarray with the end of the first element and the largest.
Assuming that for element I, all the lengths of the sub-arrays that end with its preceding elements have been evaluated, then the contiguous subarray that ends with the first element and the largest is actually either the i-1 of the first element and the largest contiguous subarray plus the element, or it contains only the I-element, or sum[i] = max ( SUM[I-1] + a[i], a[i]).
The choice can be made by judging whether Sum[i-1] + a[i] is greater than a[i], which is actually equivalent to judging whether sum[i-1] is greater than 0.
Since each operation requires only the previous result, it is not necessary to keep all the previous results as normal dynamic planning, only the last one, so the algorithm has very little time and space complexity.
The code is as follows:
1#include <iostream>2 using namespacestd;3 4 intMain ()5 {6 intn, num;7 Longsum, max;8CIN >>N;9CIN >>sum;TenMax =sum; One for(inti =1; I < n; i++) A { -CIN >>num; - if(Sum >0) theSum + =num; - Else -sum =num; - if(Sum >max) +Max =sum; - } + Acout <<Max; at - return 0; -}
Reference:http://www.cnblogs.com/waytofall/archive/2012/04/10/2439820.html
Maximum sub-array and