The maximum continuous interval and is a classic problem. Given a sequence of length n [a[1],a[2]...a[n-1],a[n], to find a continuous subsequence a[i],a[i+1]...a[j-1],a[j], making A[i]+a[i+1]...a[j-1]+a[j] the largest.
① the simplest and easiest to think about is to enumerate by definition.
Enumerates the upper bound {i,j | 0<=i<=j<=n}, maintaining a max value.
The time complexity of enumerating the upper and lower bounds is O (n^2), and the complexity of the interval and is O (n), so the total time complexity is O (n^3).
for (int i = 1; I <= n; i++)
for (int j = i; J <= N; j + +)
ans = max (ans,accumulate (a+i,a+j+1,0));
② is actually the first method of optimization.
Here is a very easy to think of the optimization, that is, preprocessing the prefix and Sum[i]=a[0]+a[1]+...+a[i-1]+a[i], the interval and the time to calculate the interval and the complexity to O (1), the enumeration of the upper and lower bounds of the complexity of the same, so the total time complexity of O (n^2).
for (int i = 1; I <= n; i++)
Sum[i]=sum[i-1]+a[i];
for (int i = 1; I <= n; i++)
for (int j = i; J <= N; j + +)
ans = max (ans,sum[j]-sum[i-1]);
③ can use the dynamic programming thinking to continue to optimize, to obtain a linear algorithm, is also the largest continuous interval and the standard algorithm
Define Maxn[i] is the maximum continuous with the end of I, it is easy to find a recursive relationship: Maxn[i]=max{0,maxn[i-1]}+a[i].
So you just need to scan it again, the total time complexity is O (n).
for (int i = 1; I <= n; i++)
{
last = max (0,last) +a[i];
ans = max (ans,last);
}
④ also uses similar thinking.
First you also need to preprocess the prefix and sum[i], you can launch Ans=max{sum[i]-min{sum[j]} | 0<=j<i<=n}.
The total time complexity is O (n), while the minimum prefix and the dynamic maintenance are maintained.
for (int i = 1; I <= n; i++)
Sum[i]=sum[i-1]+a[i];
for (int i = 1; I <= n; i++)
{
ans = max (Ans,sum[i]-minn);
Minn = min (Minn,sum[i]);
}
Summary: Although the simple O (n^3) and prefix and optimized O (n^2) algorithm is easy to think of, but the code implementation is rather than the method of three trouble, the fourth method, although there is the same complexity as the method three, but requires a preprocessing and the extra O (n) space, so, method three is very good and powerful.
Summary of algorithms for maximal continuous intervals (RPM)