#include<bits/stdc++.h>
using namespace std;
#define maxx 50009
struct node
{
long pre;
long suff;
long sum;
long maxsum;
};
struct node tree[4*maxx];
node merge(node &a,node &b)
{
node temp;
temp.sum=a.sum+b.sum;
temp.pre=max(a.pre,a.sum+b.pre);
temp.suff=max(b.suff,b.sum+a.suff);
temp.maxsum=max(a.maxsum,max(a.suff+b.pre,b.maxsum));
return temp;
}
void build(int a[],int pos,int low,int high)
{
if(low==high)
{
tree[pos].maxsum=a[low];
tree[pos].sum=a[low];
tree[pos].pre=a[low];
tree[pos].suff=a[low];
}
else
{
int mid=(low+high)/2;
build(a,2*pos,low,mid);
build(a,2*pos+1,mid+1,high);
tree[pos]=merge(tree[2*pos],tree[2*pos+1]);
}
}
node query(int pos,int low,int high,int qlow,int qhigh)
{
if(qlow>=low && qhigh<=high)
{ return tree[pos];}
int mid=(low+high)/2;
node l=query(2*pos,low,mid,qlow,qhigh);
node r=query(2*pos+1,mid+1,high,qlow,qhigh);
tree[pos]=merge(l,r);
return tree[pos];
}
int main()
{
int n;
cin>>n;
int a[maxx];
for(int i=0;i<n;i++)cin>>a[i];
build(a,0,0,n-1);
int Q;
cin>>Q;
while(Q--)
{
int x,y;
cin>>x>>y;
x-=1;
y-=1;
cout<<query(0,0,n-1,x,y).maxsum<<endl;
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKI2RlZmluZSBtYXh4IDUwMDA5CnN0cnVjdCBub2RlCnsKICAgIGxvbmcgcHJlOwogICAgbG9uZyBzdWZmOwogICAgbG9uZyBzdW07CiAgICBsb25nIG1heHN1bTsKfTsKc3RydWN0IG5vZGUgdHJlZVs0Km1heHhdOwpub2RlIG1lcmdlKG5vZGUgJmEsbm9kZSAmYikKewogICAgbm9kZSB0ZW1wOwogICAgdGVtcC5zdW09YS5zdW0rYi5zdW07CiAgICB0ZW1wLnByZT1tYXgoYS5wcmUsYS5zdW0rYi5wcmUpOwogICAgdGVt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