【问题描述】

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

 

【解题报告】

求一个整数串的两个不相交字串的和的最大值。数据范围30组N<=50000。

用O(N2)肯定超时 被虐了一上午才写出O(N)。

 1 program poj2479;
2 var
3 n,ans,t,k,i:longint;
4 lmaxn,rmaxn,lmax,rmax,a:array[0..50001]of longint;
5
6 function max(a,b:longint):longint;
7 begin
8 if a>b then exit(a);
9 exit(b);
10 end;
11
12 procedure main;
13 begin
14 readln(t);
15 for k:=1 to t do
16 begin
17 read(n);
18 for i:=1 to n do read(a[i]);
19 lmax[1]:=a[1];
20 lmaxn[1]:=a[1];
21 for i:=2 to n do lmax[i]:=max(lmax[i-1]+a[i],a[i]);
22 for i:=2 to n do lmaxn[i]:=max(lmaxn[i-1],lmax[i]);
23 rmax[n]:=a[n];
24 rmaxn[n]:=a[n];
25 for i:=n-1 downto 1 do rmax[i]:=max(rmax[i+1]+a[i],a[i]);
26 for i:=n-1 downto 1 do rmaxn[i]:=max(rmaxn[i+1],rmax[i]);
27 ans:=-maxlongint;
28 for i:=1 to n-1 do ans:=max(ans,lmaxn[i]+rmaxn[i+1]);
29 writeln(ans);
30 end;
31 end;
32
33 begin
34 main;
35 end.
36