分治加二分
#include<bits/stdc++.h>
using namespace std;typedef unsigned long long ull;typedef long long ll;const ll N=1e5+7,inf=1e18;
ull ans,lssum[N],rssum[N];int n,i,j,a[N];ll lsum[N],rsum[N],lmx[N],rmx[N];
int fr(ll x,int l,int r){
int ans=r+1;while(l<=r){
int mid=l+r>>1;rsum[mid]>=x?r=(ans=mid)-1:l=mid+1;
}return ans;
}
int fl(ll x,int l,int r){
int ans=l-1;while(l<=r){
int mid=l+r>>1;lsum[mid]>=x?l=(ans=mid)+1:r=mid-1;
}return ans;
}
void dfs(int l,int r){
if(l==r)return ans+=a[l],void();int mid=l+r>>1;dfs(l,mid);dfs(mid+1,r);
ll sum=0,mx=0;int i,L,R,x;
for(lssum[mid+1]=0,lsum[mid+1]=lmx[mid+1]=-inf,i=mid;i>=l;--i){
lsum[i]=max(lsum[i+1],sum+=a[i]);
lmx[i]=max(lmx[i+1],mx+=a[i]);mx<0?(mx=0):0;
lssum[i]=lssum[i+1]+lsum[i];
}sum=mx=0;
for(rssum[mid]=0,rsum[mid]=rmx[mid]=-inf,i=mid+1;i<=r;++i){
rsum[i]=max(rsum[i-1],sum+=a[i]);
rmx[i]=max(rmx[i-1],mx+=a[i]);mx<0?(mx=0):0;
rssum[i]=rssum[i-1]+rsum[i];
}
for(L=mid,R=mid+1;L>=l||R<=r;){
if(R>r||(L>=l&&lmx[L]<rmx[R])){
x=fr(lmx[L]-lsum[L],mid+1,R-1);
ans+=lmx[L]*(x-mid-1)+lsum[L]*(R-x)+rssum[R-1]-rssum[x-1];
L--;
}else{
x=fl(rmx[R]-rsum[R],L+1,mid);
ans+=rmx[R]*(mid-x)+rsum[R]*(x-L)+lssum[L+1]-lssum[x+1];
R++;
}
}
}
int main(){
for(scanf("%d",&n),i=1;i<=n;++i)scanf("%d",a+i);dfs(1,n);cout<<ans<<endl;
}