给定长度为n的数组b,求对于任意1<=l<=r<=n, 求b[i] + b[j] + b[k] - (r - l) 的最大值(l<=i, j, k<=r)

题目

思路:

给定长度为n的数组b,求对于任意1<=l<=r<=n, 求b[i] + b[j] + b[k] - (r - l) 的最大值(l<=i, j, k<=r)_第1张图片

#include 
using namespace std;
#define int long long
#define pb push_back
#define fi first
#define se second
#define lson p << 1
#define rson p << 1 | 1
const int maxn = 1e6 + 5, inf = 1e18 + 5, maxm = 4e4 + 5, mod = 1e9 + 7, N = 1e6;
int a[maxn], b[maxn];
bool vis[maxn];
int n, m;
string s;
int pre[maxn];
int suf[maxn];

void solve(){
    int res = 0;
    int k;
    int x;
    int q;
    cin >> n;
    for(int i = 1; i <= n; i++){
        cin >> b[i];
    }
    for(int i = 1; i <= n; i++){
        pre[i] = max(pre[i - 1], b[i] + i);
    }
    suf[n + 1] = -inf;
    for(int i = n; i >= 1; i--){
        suf[i] = max(suf[i + 1], b[i] - i);
    }
    for(int i = 2; i < n; i++){
        res = max(res, pre[i - 1] + suf[i + 1] + b[i]);
    }
    cout << res << '\n';
}
    
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T = 1;
    cin >> T;
    while (T--)
    {
        solve();
    }
    return 0;
}

你可能感兴趣的:(codeforces,算法)