每个物品售价x原价a[i]则优惠了a[i] - x元

求买连续一段物品的最大优惠之和,即为求连续一段元素a[i] - x之和的最大值

对a[i] - x求前缀和,枚举i作为右端点,减去一个前面的最小前缀和更新答案即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 2e5 + 10;
int a[N], n, x;
LL sum[N];
int main() {
    cin >> n >> x;
    LL t = 0, ans = 0;
    for (int i = 1; i <= n; i ++) {
        cin >> a[i];
        a[i] -= x;
        sum[i] = sum[i - 1] + a[i];
        ans = max(ans, sum[i] - t);
        t = min(t, sum[i]);
    }
    cout << ans;
    return 0;
}