Three Parts of the Array

You are given an array d1,d2,…,dn consisting of n 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 sum1, the sum of elements of the second part be sum2 and the sum of elements of the third part be sum3. Among all possible ways to split the array you have to choose a way such that sum1=sum3 and sum1 is maximum possible.

More formally, if the first part of the array contains a elements, the second part of the array contains b elements and the third part contains c elements, then:

sum1= ∑1≤i≤a di,
sum2= ∑a+1≤i≤a+b di,
sum3= ∑a+b+1≤i≤a+b+c di.
The sum of an empty array is 0.

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

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

The second line of the input contains n integers d1,d2,…,dn (1≤di≤109) — the elements of the array d.

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

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

Examples
Input
5
1 3 1 1 4
Output
5
Input
5
1 3 2 1 4
Output
4
Input
3
4 1 2
Output
0
Note
In the first example there is only one possible splitting which maximizes sum1: [1,3,1],[ ],[1,4].

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

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

这个题目我的思路是从两边开始分别相加,保留和,当两个和相等的话就保留这个和。继续走,直到两个相遇。中间遇到更大的就保留下来。但是注意如果有一边比另一边大的话,另一边就继续相加。但是这一边不加,这点很重要。

#include<cstdio>
#include<vector>

using namespace std;

vector<int>vec;

int main()
{
    int n; scanf ("%d", &n);
    long long x;
    for (int i = 0; i < n; i++)
    {
        scanf ("%d", &x);
        vec.push_back(x);
    }
    long long sum_l = 0, sum_r = 0, max = 0;
    int ans1 = -1, ans2 = -1;
    for (int i = 0, j = n-1; i < j;)
    {
        if (ans1 != i) sum_l += vec[i];
        if (ans2 != j) sum_r += vec[j];
        ans1 = i; ans2 = j;
        if (sum_l > sum_r) j--;
        else if (sum_l < sum_r) i++;
        else
        {
            max = sum_l;
            i ++; j --;
        }

    }
    printf ("%lld\n", max);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/hqzzbh/article/details/81149623