转自https://blog.youkuaiyun.com/u013534123/article/details/87560151
#include <bits/stdc++.h>
#define INF 1e18
#define fi first
#define se second
#define LL long long
#define sc(x) scanf("%d",&x)
#define scc(x,y) scanf("%d%d",&x,&y)
#define sccc(x,y,z) scanf("%d%d%d",&x,&y,&z)
using namespace std;
const int N = 200010;
LL s[N],f[N],w[N];
int a[N],q[N],n;
inline LL Y(int x)
{
return w[x];
}
inline LL X(int x)
{
return x;
}
inline bool judge(int j,int k,int i)
{
return Y(j)-Y(k)>=(X(j)-X(k))*s[i];
}
bool maintain(int i,int j,int k)
{
return (Y(k)-Y(i))*(X(i)-X(j))>(Y(i)-Y(j))*(X(k)-X(i));
}
int main()
{
sc(n);
for(int i=1;i<=n;i++)
{
sc(a[i]);
s[i]=s[i-1]+a[i];
f[i]=f[i-1]+(LL)i*a[i];
w[i]=(LL)i*s[i]-f[i];
}
LL ans=-1e18;
int h=0,t=1;
for(int i=1;i<=n;i++)
{
while (h<t&&judge(q[h+1],q[h],i)) h++;
while (h>0&&judge(q[h-1],q[h],i)) h--;
ans=max(ans,f[i]-q[h]*s[i]+w[q[h]]);
while (t>1&&maintain(q[t],q[t-1],i)) t--;
q[++t]=i;
}
printf("%lld\n",ans);
return 0;
}