1. 程式人生 > >C. Three Parts of the Array(切割字串)

C. Three Parts of the Array(切割字串)

                                                                 C. Three Parts of the Array

You are given an array d1,d2,…,dnd1,d2,…,dn consisting of nn integer numbers.

Your task is to split this array into three parts (some of which may be empty) in such a way that each element of the array belongs to exactly one of the three parts, and each of the parts forms a consecutive contiguous subsegment (possibly, empty) of the original array.

Let the sum of elements of the first part be sum1sum1 , the sum of elements of the second part be sum2sum2 and the sum of elements of the third part be sum3sum3 . Among all possible ways to split the array you have to choose a way such that sum1=sum3sum1=sum3 and sum1sum1 is maximum possible.

More formally, if the first part of the array contains aa elements, the second part of the array contains bb elements and the third part contains cc elements, then:    

The sum of an empty array is 00 .

Your task is to find a way to split the array such that sum1=sum3sum1=sum3 and sum1sum1 is maximum possible.

Input

The first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105 ) — the number of elements in the array dd .

The second line of the input contains nn integers d1,d2,…,dnd1,d2,…,dn (1≤di≤1091≤di≤109 ) — the elements of the array dd .

Output

Print a single integer — the maximum possible value of sum1sum1 , considering that the condition sum1=sum3sum1=sum3 must be met.

Obviously, at least one valid way to split the array exists (use a=c=0a=c=0 and b=nb=n ).

Examples

Input

Copy

5
1 3 1 1 4

Output

Copy

5

Input

Copy

5
1 3 2 1 4

Output

Copy

4

Input

Copy

3
4 1 2

Output

Copy

0

Note

In the first example there is only one possible splitting which maximizes sum1sum1 : [1,3,1],[ ],[1,4][1,3,1],[ ],[1,4] .

In the second example the only way to have sum1=4sum1=4 is: [1,3],[2,1],[4][1,3],[2,1],[4] .

In the third example there is only one way to split the array: [ ],[4,1,2],[ ][ ],[4,1,2],[ ] .

題意:將一個字串劃分為三段,使得子字串的和分別為sum1、sum2、sum3,使得sum1 == sum3,且sum1儘可能的大,輸出sum1.

題解:這道題剛開始自己思緒很混亂,不知道該如何下手,後來才知道。從兩邊向中間推,找到最大的sum1.(感覺程式碼很考驗技巧性。需要學習這種技巧)

#include<cstdio>
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn = 2*1e5+5;
long long d[maxn];
int main()
{
	int n;
	scanf("%d", &n);
	for(int i = 0; i < n; i++) scanf("%lld", &d[i]);
	
	long long sum1 = 0, sum2 = 0, mx = 0;
	int i = 0, j = n-1;
	//從兩邊往中間推 
	while(i <= j){
		if(sum1 < sum2){      //當sum1較小時,i向前推,同時sum1加值 
			sum1 += d[i];
			i++;
		}
		if(sum1 > sum2){
			sum2 += d[j];    //當sum2較小時,j向後推,同時sum2加值 
			j--;
		}
		if(sum1 == sum2){
			if(sum1 > mx){   //當兩邊相等時,取最大的sum值 
				mx = sum1;
			}
			sum1 += d[i];
			i++;
		}                //一次類推,一直到跳出迴圈 
	}
	printf("%lld\n", mx);
	return 0;
}