#include <bits/stdc++.h>
using namespace std;
struct SparseMin {
int n; vector<int> lg; vector<vector<int>> st;
void build(const vector<int>& a){ // a is 1-indexed, size n+1
n = (int)a.size() - 1;
lg.assign(n+1,0);
for(int i=2;i<=n;i++) lg[i]=lg[i/2]+1;
st.assign(lg[n]+1, vector<int>(n+1));
for(int i=1;i<=n;i++) st[0][i]=a[i];
for(int k=1;k<=lg[n];k++){
int len=1<<(k-1);
for(int i=1;i+(1<<k)-1<=n;i++)
st[k][i]=min(st[k-1][i], st[k-1][i+len]);
}
}
inline int query(int l,int r) const{ // inclusive
if(l>r) return INT_MAX;
int k=lg[r-l+1];
return min(st[k][l], st[k][r-(1<<k)+1]);
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n; if(!(cin>>n)) return 0;
vector<int>a(n+1);
for(int i=1;i<=n;i++) cin>>a[i];
int q; cin>>q;
vector<pair<int,int>> Q(q);
for(int i=0;i<q;i++) cin>>Q[i].first>>Q[i].second;
const int A=100;
// positions by value
vector<vector<int>> pos(A+1);
for(int i=1;i<=n;i++) pos[a[i]].push_back(i);
vector<long long> ans(q,0);
// arrays reused per k
vector<int> Sk(n+1), Ck(n+1), Uk(n+1);
for(int k=1;k<=A;k++){
// prefix counts of value k
Ck[0]=0;
for(int i=1;i<=n;i++) Ck[i]=Ck[i-1]+(a[i]==k);
// S_k: (<k => +a, >=k => -a)
Sk[0]=0;
for(int i=1;i<=n;i++) Sk[i]=Sk[i-1] + (a[i]<k ? a[i] : -a[i]);
// U_k = S_k + 2k * Ck
for(int i=0;i<=n;i++) Uk[i]=Sk[i] + 2*k*Ck[i];
SparseMin RMQ_S, RMQ_U;
RMQ_S.build(Sk);
RMQ_U.build(Uk);
const auto& P = pos[k];
for(int id=0; id<q; id++){
int L=Q[id].first, R=Q[id].second;
int tot = Ck[R]-Ck[L-1];
if(tot==0) continue;
int base = int(lower_bound(P.begin(), P.end(), L) - P.begin()); // first k in [L..]
// check if the block really fits inside [L,R]
// (by constraints of tot it must)
auto ok = [&](int m)->bool{
// pos_m: position of m-th k inside [L,R]; pos_0 = L-1
int pos_m = (m==0 ? L-1 : P[base + m - 1]);
// v1: for t in [L .. pos_m], x(t) = (Uk[t] - const0) must be >= 0
int v1 = INT_MAX;
if(pos_m >= L){
int minU = RMQ_U.query(L, pos_m);
int const0 = Sk[L-1] + 2*k*Ck[L-1];
v1 = minU - const0;
}
// v2: for t in [pos_m+1 .. R], x(t) = (Sk[t]-Sk[L-1]) + 2k*m >= 0
int left2 = max(L, pos_m+1);
int minS = RMQ_S.query(left2, R);
int v2 = (minS==INT_MAX ? INT_MAX : (minS - Sk[L-1] + 2*k*m));
return min(v1, v2) >= 0;
};
// binary search minimal rescued m in [0..tot]
int lo=0, hi=tot, res=tot;
while(lo<=hi){
int mid=(lo+hi)>>1;
if(ok(mid)){ res=mid; hi=mid-1; }
else lo=mid+1;
}
ans[id] += (tot - res); // rescued are additions; gifts are the rest
}
}
for(int i=0;i<q;i++) cout<<ans[i]<<"\n";
return 0;
}