#pragma GCC optimize("O3","unroll-loops") #pragma GCC target("sse4,tune=native") #include using namespace std; typedef long long ll; typedef double ld; const int INF = (int) 1e9 + 1e6; const ll LINF = (ll) 1e18 + 1e9; const ld EPS = (ld) 1e-10; const ll MOD = (ll) 1e9 + 7; #define sz(x) (int) (x).size() #define mp(x, y) make_pair(x, y) #define pb push_back #define all(x) (x).begin(), (x).end() #define lb(s, t, x) (int) (lower_bound(s, t, x) - s) #define ub(s, t, x) (int) (upper_bound(s, t, x) - s) #define rep(i, f, t) for (auto i = f; i < t; ++(i)) #define per(i, f, t) for (auto i = (f); i >= (t); --(i)) ll power(ll x, ll y, ll mod = MOD) { if (y == 0) { return 1; } if (y & 1) { return power(x, y - 1, mod) * x % mod; } else { ll tmp = power(x, y / 2, mod); return tmp * tmp % mod; } } template bool mini(A &x, const B &y) { if (y < x) { x = y; return true; } return false; } template bool maxi(A &x, const B &y) { if (y > x) { x = y; return true; } return false; } void run(); #define TASK "" int main() { #ifdef LOCAL if (strlen(TASK) > 0) { cerr << "Reminder: you are using file i/o, filename: " TASK "!" << endl << endl; } #endif #ifndef LOCAL if (strlen(TASK)) { freopen(TASK ".in", "r", stdin); freopen(TASK ".out", "w", stdout); } ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); #endif cout << fixed << setprecision(12); run(); return 0; } // == SOLUTION == // struct Line { ll k, b; ll value(ll x) const { return k * x + b; } bool operator<(const Line &l) const { if (k != l.k) { return k < l.k; } return b > l.b; } }; const int N = (int) 5e5 + 123; int n; int a[N]; ll ans = -LINF; vector tmp; vector lines; vector points; ll div_up(ll x, ll y) { if (y < 0) { x = -x; y = -y; } if (x < 0) { return x / y; } else { return (x + y - 1) / y; } } ll inter(Line a, Line b) { return div_up(b.b - a.b, a.k - b.k); } void add(Line l) { if (sz(lines) && lines.back().k == l.k) { return; } while (sz(points) && points.back() >= inter(l, lines.back())) { points.pop_back(); lines.pop_back(); } if (sz(lines)) { points.pb(inter(lines.back(), l)); } lines.pb(l); } ll get(ll x) { int ind = (int) (upper_bound(all(points), x) - points.begin()); return lines[ind].value(x); } void build() { lines.clear(); points.clear(); sort(all(tmp)); for (auto &l : tmp) add(l); tmp.clear(); } void solve(int l, int r) { if (l >= r) return; if (r - l <= 5) { rep(i, l, r) { ll res = 0; ll sum = 0; rep(j, i, r) { res += a[j] * sum; sum += a[j]; maxi(ans, res); } } return; } int mid = (l + r) / 2; solve(l, mid); solve(mid, r); ll res = 0; ll sum = 0; per(i, mid - 1, l) { res += a[i] * sum; sum += a[i]; tmp.pb({sum, res}); } build(); res = 0; sum = 0; rep(i, mid, r) { res += a[i] * sum; sum += a[i]; ll cur = res + get(sum); maxi(ans, cur); } } void run() { cin >> n; rep(i, 0, n) { cin >> a[i]; } solve(0, n); cout << ans << "\n"; }