# way1(枚舉+最大子段和)

$a[i]$的範圍很小，所以可以從這方面入手，我們可以枚舉最大值$[0,30]$，然後做一個貪心的最大字段和。

if(a[i]>v||sum<0)sum = 0;


#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 2e5+10;
#define IOS ios::sync_with_stdio(0)
#define ull unsigned ll
#define uint unsigned
#define pai pair<int,int>
#define pal pair<ll,ll>
#define IT iterator
#define pb push_back
#define fi first
#define se second
#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);++i)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);--i)
#define endl '\n'
#define ll long long
const ll mod = 1e9+7;
int a[man];

int main() {
#ifndef ONLINE_JUDGE
//freopen("in.txt", "r", stdin);
//freopen("out.txt","w",stdout);
#endif
int n;
scanf("%d",&n);
For(i,1,n){
scanf("%d",a+i);
}
int ans = 0;
For(v,0,30){
int sum = 0;
For(i,1,n){
sum += a[i];
if(a[i]>v||sum<0)sum = 0;
ans = max(ans,sum - v);
}
}
printf("%d\n",ans);
return 0;
}


# way2(單調棧+線段樹)

#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
const int man = 2e5+10;
#define IOS ios::sync_with_stdio(0)
#define ull unsigned ll
#define uint unsigned
#define pai pair<int,int>
#define pal pair<ll,ll>
#define IT iterator
#define pb push_back
#define fi first
#define se second
#define For(i,j,k) for (int i=(int)(j);i<=(int)(k);++i)
#define Rep(i,j,k) for (int i=(int)(j);i>=(int)(k);--i)
#define endl '\n'
#define ll long long
const ll mod = 1e9+7;
int a[man],sum[man];
int ma[man<<2],mi[man<<2];
int _l[man],_r[man],sta[man];

inline void pushup(int rt){
ma[rt] = max(ma[rt<<1],ma[rt<<1|1]);
mi[rt] = min(mi[rt<<1],mi[rt<<1|1]);
}

inline void build(int l,int r,int rt){
ma[rt] = mi[rt] = 0;
if(l==r){
ma[rt] = mi[rt] = sum[l];
return;
}
int m = l + r >>1;
build(l,m,rt<<1);
build(m+1,r,rt<<1|1);
pushup(rt);
}

void query(int l,int r,int L,int R,int rt,int op,int &ans){
if(L<=l&&R>=r){
if(op){
ans = max(ans,ma[rt]);
}else ans = min(ans,mi[rt]);
return;
}
int m = l + r >> 1;
if(L<=m)query(l,m,L,R,rt<<1,op,ans);
if(R>m)query(m+1,r,L,R,rt<<1|1,op,ans);
}

int main() {
#ifndef ONLINE_JUDGE
//freopen("in.txt", "r", stdin);
//freopen("out.txt","w",stdout);
#endif
int n;
scanf("%d",&n);
For(i,1,n){
scanf("%d",a+i);
sum[i] = sum[i-1] + a[i];
}
a[0] = a[n+1] = 1e9;
int top = 0;
sta[++top] = 0;
For(i,1,n){
while(top>=1&&a[i]>=a[sta[top]])--top;
_l[i] = sta[top];
sta[++top] = i;
}
top = 0;
sta[++top] = n+1;
Rep(i,n,1){
while(top>=1&&a[i]>=a[sta[top]])--top;
_r[i] = sta[top];
sta[++top] = i;
}
build(0,n,1);
int ans = 0;
For(i,1,n){
int res1 = -1e9,res2 = 1e9;
query(0,n,i,_r[i]-1,1,1,res1);
query(0,n,_l[i],i-1,1,0,res2);
ans = max(ans,res1 - res2 - a[i]);
}
printf("%d\n",ans);
return 0;
}