poj-2479


题目

题面

Maximum sum
Time Limit: 1000MS
Memory Limit: 65536K
Description
avatar

Given a set of n integers: A={a1, a2,…, an}, we define a function d(A) as below:
Your task is to calculate d(A).

Input

The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, …, an. (|ai| <= 10000).There is an empty line after each case.

Output

Print exactly one line for each test case. The line should contain the integer d(A).

Examples

Input

1
10
1 -1 2 2 3 -3 4 -4 5 -5

Output

13

Hint

In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.

Huge input,scanf is recommended

思路

这个题目也是一个最大和问题但是又不太一样,这个是从两边开始的,求的是两边最大和的最大值,所以说要在中间找一个点作为分割点(一个个试),再求两边的最大和,但是用之前的那个方法一个个算会超时,所以说我们建立两个数组,来记录每个点两边的最大和,即可一步完成

代码

#include<stdio.h>
#include<algorithm>
using namespace std;
#define MIN -0x3f3f3f3f
int main()
{
    int a[50010],left[50010],right[50010];
    int n;
    //freopen("F:/y.txt","r",stdin);
    int t;
    scanf("%d",&t);
    while(t--)
    {
       scanf("%d",&n);
       for(int i=0;i<n;i++)
       {
           scanf("%d",&a[i]);
       }
       left[0]=a[0];
       for(int i=1;i<n;i++)
       {
           if(left[i-1]>0)
           left[i]=left[i-1]+a[i];
           else
           left[i]=a[i];
       }
       for(int i=1;i<n;i++)
       {
           if(left[i]<left[i-1])
           left[i]=left[i-1];
       }
       right[n-1]=a[n-1];
       for(int i=n-2;i>=0;i--)
       {
           if(right[i+1]>0)
           right[i]=right[i+1]+a[i];
           else
           right[i]=a[i];
      }
       for(int i=n-2;i>=0;i--)
       if(right[i]<right[i+1])
       right[i]=right[i+1];
       int max1=MIN;
       for(int i=0;i<n-1;i++)
       {
           max1=max(max1,left[i]+right[i+1]);
       }
       printf("%d\n",max1);
    }
    return 0;
}

文章作者: xucanxx
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 xucanxx !
  目录