Maximum sum

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 39089   Accepted: 12221

Description

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).

Sample Input

1

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

Sample 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.

分别求出两端开始的最大子段和,然后枚举左右两段的分界,找出最大值。

 //2016.8.21
#include<iostream>
#include<cstdio>
#include<cstring> using namespace std; const int N = ;
const int inf = 0x3f3f3f3f;
int a[N], dpl[N], dpr[N];//dpl[i]表示从左往右到第i位的最大子段和,dpr[i]表示从右往左到第i位的最大子段和 int main()
{
int T, n;
cin>>T;
while(T--)
{
scanf("%d", &n);
for(int i = ; i < n; i++)
{
scanf("%d", &a[i]);
}
memset(dpl, , sizeof(dpl));
memset(dpr, , sizeof(dpr));
//从左往右扫
//*************************************************
dpl[] = a[];
for(int i = ; i < n; i++)
if(dpl[i-]>) dpl[i] = dpl[i-]+a[i];
else dpl[i] = a[i];
for(int i = ; i < n; i++)
if(dpl[i]<dpl[i-])
dpl[i] = dpl[i-];
//从右往左扫
//*************************************************
dpr[n-] = a[n-];
for(int i = n-; i>=; i--)
if(dpr[i+]>) dpr[i] = dpr[i+]+a[i];
else dpr[i] = a[i];
for(int i = n-; i>=; i--)
if(dpr[i]<dpr[i+])
dpr[i] = dpr[i+];
//*************************************************
int ans = -inf;
for(int i = ; i < n-; i++)
{
ans = max(ans, dpl[i]+dpr[i+]);
}
cout<<ans<<endl;
} return ;
}

最新文章

  1. 报错注入分析之updatexml注入
  2. App Widget
  3. Eclipse自动编译问题
  4. git github 异常
  5. Redis设计与实现-附加功能
  6. stanford-postagger中文词性标注
  7. 通俗易懂的讲解iphone视图控制器的生命周期
  8. js中对象调用对象中的方法
  9. SQLserver 数据库
  10. jQuery工作原理解析以及源代码示例
  11. 《VIM-Adventures攻略》前言
  12. 1号店Interview小结
  13. 2015 Multi-University Training Contest 3
  14. TS学习随笔(五)-&gt;函数
  15. EFI系统引导的一些零碎知识点
  16. s9.16作业,员工信息表
  17. Flask学习【第5篇】:用Falsk实现的分页
  18. LOJ 2553 「CTSC2018」暴力写挂——边分治+虚树
  19. GetFileOpenName()、GetFilesavename
  20. navicat连接mysql报10061错

热门文章

  1. CSS中的浮动清除
  2. linux下 mysql 学习(一)
  3. HUST 1351 Group
  4. 一次性能优化,tps从400+到4k+
  5. spring调用mongodb
  6. STM8S STM8L引脚如何配置最低(转)
  7. iOS开发之监听键盘高度的变化
  8. iOS开发——点击图片全屏显示
  9. LPC1768基本输入输出GPIO使用
  10. ios 简单的plist文件读写操作(Document和NSUserDefaults)