Base Time Limit: 1 second Space Limit: 131072 KB Score: 10Difficulty
: Level 2 Algorithm Questions
collect
focus on
A cyclic sequence a[1],a[2],a[3],…,a[n] composed of N integers, find the sequence such as a[i]+a[i+1]+…+a[j ] The maximum value of the sum of consecutive sub-segments (cyclic sequence refers to n numbers enclosing a circle, so it is necessary to consider the sequence of a[n-1], a[n], a[1], a[2] ). The sum is 0 when all of the given integers are negative.
For example: -2,11,-4,13,-5,-2, and the largest subsegments are: 11,-4,13. and 20.
Input
Line 1: Length N of integer sequences (2 <= N <= 50000) Lines 2 - N+1: N integers (-10^9 <= S[i] <= 10^9)
Output
Output the largest sum of subsections of a circular array.
Input example
6 -2 11 -4 13 -5 -2
Output example
20
[Code]:
#include<cstdio> #include<cstring> #include<queue> #include<iostream> #include<stack> #define maxn 1005 #define maxm 50005 #define INF 0x3f3f3f3f #define ll long long using namespace std; int n; ll a[maxm]; // One is that the maximum value is not out of bounds, then it is the largest continuous subsection and ll Max( int n) { ll dp[maxm];dp[0]=0; ll ans=0; for(int i=1;i<=n;i++){ if(dp[i-1]>0) dp[i]=dp[i-1]+a[i]; else dp[i]=a[i]; ans=max(ans,dp[i]); } return ans; } // The other is out of bounds. At this time, we can change our thinking and ask for the sum of the largest consecutive sub-segments that are out of bounds ---> We can find the sum of the smallest consecutive sub-segments that cannot be out of bounds, so that the remaining numbers sum is not But the largest and is continuous across the border. // sum - not bounding the smallest consecutive subsegment sum 23 5 -9 -18 -7 6 ll Min( int n) { ll dp[maxm];dp[0]=0; ll ans=0; for(int i=1;i<=n;i++){ if(dp[i-1]<0) dp[i]=dp[i-1]+a[i]; else dp[i]=a[i]; yrs = min(yrs,dp[i]); } return ans; } intmain () { scanf("%d",&n); ll sum=0; for(int i=1;i<=n;i++){ scanf("%lld",&a[i]); sum += a[i]; } printf("%lld\n",max(Max(n),sum-Min(n))); return 0; }