Summary of the algorithm for the largest continuous interval sum

click on the link

③ You can use the thinking of dynamic programming to continue to optimize, and get a linear algorithm, which is also the standard algorithm of the maximum continuous interval sum.
Define maxn[i] as the maximum continuous sum ending with i, then it is easy to find the recurrence relationship: maxn[ i]=max{0,maxn[i-1]}+a[i].
So it only needs to scan once, and the total time complexity is O(n).
for ( int i = 1 ; i <= n ; i++ )
{
    last = max(0,last)+a[i];
    ans = max(ans,last);
}
④Similar thinking is also used.
First, the prefix and sum[i] need to be preprocessed, and ans=max{sum[i]-min{sum[j] } | 0<=j<i<=n } can be derived.
And the minimum prefix sum can be maintained dynamically, so the total time complexity is O(n).
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]);
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325398929&siteId=291194637