#include <bits/stdc++.h>
#define ar array
//#define int long long
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
const int mod = 1e9 + 7;
const ll inf = 1e18;
const int maxn = 1e5 + 5;
signed main() {
ios_base::sync_with_stdio(false);
cout.tie(0); cin.tie(0);
int n, q; cin >> n;
vector<int> a(n+1);
for(int i=1; i<=n; i++) cin >> a[i];
vector<pii> imp;
stack<int> st;
for(int i=n; i>=1; i--) {
while(!st.empty() && a[st.top()] < a[i]) st.pop();
if(!st.empty()) imp.push_back({ i, st.top() });
st.push(i);
}
while(!st.empty()) st.pop();
for(int i=n; i>=1; i--) {
while(!st.empty() && a[st.top()] >= a[i]) st.pop();
if(!st.empty()) imp.push_back({ i, st.top() });
st.push(i);
}
while(!st.empty()) st.pop();
for(int i=1; i<=n; i++) {
while(!st.empty() && a[st.top()] < a[i]) st.pop();
if(!st.empty()) imp.push_back({ st.top(), i });
st.push(i);
}
while(!st.empty()) st.pop();
for(int i=1; i<=n; i++) {
while(!st.empty() && a[st.top()] >= a[i]) st.pop();
if(!st.empty()) imp.push_back({ st.top(), i });
st.push(i);
}
cin >> q;
while(q--) {
int l, r, ans = 0; cin >> l >> r;
for(auto [x, y] : imp) {
if(x < l || y > r) continue;
for(int i=y+y-x; i<=r; i++)
ans = max(ans, a[x] + a[y] + a[i]);
}
cout << ans << '\n';
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |