#include <bits/stdc++.h>
#define ll long long
#define ldb long double
#define endl '\n'
#define For(i,l,r) for(int i=l;i<=r;i++)
#define ForD(i,r,l) for(int i=r;i>=l;i--)
#define ff first
#define ss second
#define pb push_back
#define all(x) x.begin(),x.end()
#define sz(x) (signed)x.size()
#define unq(x) x.resize(unique(all(x))-x.begin())
#define F "TASK"
#define fio freopen(F".INP","r",stdin);freopen(F".OUT","w",stdout);
#ifdef NCGM
#include"debug.h"
#else 
#define debug(...) "fr";
#endif
using namespace std;
int n,q,a[103],mx[103][103];
ll calM(int x,int l,int r) {
    ll ans=-1e18;
    int kk=mx[l][x-1];
    ForD(i,x-1,l) {
        int dis=x-i;
        if (x+dis<=r && x<r && kk==a[i]) ans=max(ans,(ll)(a[x]+a[i]+mx[x+dis][r])); 
        if (kk==a[i]) break;
    }
    kk=mx[x+1][r];
    ForD(i,r,x+1) {
        int dis=i-x;
        if (x>l && x-dis && kk==a[i]) ans=max(ans,(ll)(a[x]+a[i]+mx[max(l,x-dis)][x-1]));
        if (kk==a[i]) break;
    }
    return ans;
}
int main() {
    cin.tie(0)->sync_with_stdio(0);
    cin >> n;
    For(i,1,n) cin >> a[i];
    For(i,1,n) {
        mx[i][i]=a[i];
        For(j,i+1,n) mx[i][j]=max(mx[i][j-1],a[j]);
    }
    cin >> q;
    while(q--) {
        int l,r;
        cin >> l >> r;
        int ma=mx[l][r];
        ll ans=-1e18;
        For(i,l,r) 
            if (true) {
                ans=max(ans,calM(i,l,r));
            }
        cout << ans << endl;
    }
    return 0;
}
| # | 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... |