1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4
5 using namespace std;
6
7 int an[50010];
8 int get[50010];
9 struct Node
10 {
11 int l,r;
12 int lmax,rmax,ma;
13 int sum;
14 }bn[200000];
15
16 void build(int k,int l,int r)
17 {
18 bn[k].l=l;
19 bn[k].r=r;
20 bn[k].sum=get[r]-get[l-1];
21 if(l==r)
22 {
23 bn[k].ma=an[l];
24 bn[k].lmax=an[l];
25 bn[k].rmax=an[l];
26 return ;
27 }
28 int lk=k*2;
29 int rk=lk+1;
30 int mid=(l+r)/2;
31 build(lk,l,mid);
32 build(rk,mid+1,r);
33 bn[k].lmax=max(bn[lk].lmax,bn[lk].sum+bn[rk].lmax);
34 bn[k].rmax=max(bn[rk].rmax,bn[rk].sum+bn[lk].rmax);
35 bn[k].ma=max(bn[k].lmax,bn[k].rmax);
36 bn[k].ma=max(bn[k].ma,bn[lk].ma);
37 bn[k].ma=max(bn[k].ma,bn[rk].ma);
38 bn[k].ma=max(bn[k].ma,bn[lk].rmax+bn[rk].lmax);
39 bn[k].sum=bn[lk].sum+bn[rk].sum;
40 }
41
42 Node search(int k,int l,int r)
43 {
44 if(bn[k].l==l&&bn[k].r==r)
45 {
46 // cout<<"l"<<l<<"r"<<r<<endl;
47 // cout<<bn[k].ma<<" "<<bn[k].sum<<" "<<bn[k].lmax<<" "<<bn[k].rmax<<endl;
48 return bn[k];
49 }
50 int lk=k*2;
51 int rk=lk+1;
52 if(bn[lk].r>=r)
53 {
54 // cout<<"kk2"<<endl;
55 return search(lk,l,r);
56 }
57 else if(bn[rk].l<=l)
58 {
59 // cout<<"kk1"<<endl;
60 return search(rk,l,r);
61 }
62 else
63 {
64 // cout<<"kk"<<endl;
65 Node a=search(lk,l,bn[lk].r);
66 Node b=search(rk,bn[rk].l,r);
67 Node ret;
68 ret.sum=a.sum+b.sum;
69 ret.lmax=max(a.lmax,a.sum+b.lmax);
70 ret.rmax=max(b.rmax,b.sum+a.rmax);
71 ret.ma=max(ret.lmax,ret.rmax);
72 ret.ma=max(ret.ma,b.ma);
73 ret.ma=max(ret.ma,a.ma);
74 ret.ma=max(ret.ma,a.rmax+b.lmax);
75 // cout<<"s"<<a.lmax<<" "<<a.rmax<<" "<<a.ma<<" "<<a.sum<<endl;
76 return ret;
77 }
78 }
79
80 int main()
81 {
82 int n;
83 while(scanf("%d",&n)!=EOF)
84 {
85 memset(an,0,sizeof(an));
86 memset(get,0,sizeof(get));
87 for(int i=1;i<=n;i++)
88 {
89 scanf("%d",&an[i]);
90 }
91 for(int i=1;i<=n;i++)
92 {
93 get[i]=get[i-1]+an[i];
94 }
95 build(1,1,50010);
96 int m;
97 scanf("%d",&m);
98 int a,b;
99 for(int i=0;i<m;i++)
100 {
101 scanf("%d%d",&a,&b);
102 printf("%d\n",search(1,a,b).ma);
103 }
104 }
105 return 0;
106 }