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;
}

猜你喜欢

转载自blog.csdn.net/qq_41818544/article/details/82257669