#include <bits/stdc++.h>
using namespace std;
int main (){
#ifndef ONLINE_JUDGE
freopen("SuhaibSawalha1","r",stdin);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
long long neg = 0, pos = 0;
int idx = -1, last, first_neg = -1;
set<array<int, 2>> s;
for (int i = 0; i < n; ++i) {
int x;
cin >> x;
if (x < 0) {
neg += x;
if (first_neg == -1) {
first_neg = i;
}
}
else {
s.insert({x, i});
last = i;
}
}
if (s.empty()) {
return !(cout << neg);
}
auto it = *s.begin();
auto go = [&] (bool f) {
vector<pair<long long, int>> a;
idx = pos = 0;
for (auto e : s) {
if (e[1] > idx) {
idx = e[1];
a.push_back({e[0], e[1]});
}
else {
pos += e[0];
}
}
if (idx == last) {
a.back().first += pos;
}
else {
a.push_back({pos, 0});
}
if (f) {
a.push_back({it[0], it[1]});
}
if (neg && first_neg < a[0].second) {
a.insert(a.begin(), {neg, 0});
}
else {
a[0].first += neg;
}
while (a.size() && !a.back().first) {
a.pop_back();
}
return a;
};
auto a = go(0);
s.erase(s.begin());
auto b = go(1);
vector<pair<long long, int>> v;
for (int i = 0; i < min(a.size(), b.size()); ++i) {
if (a[i].first < b[i].first) {
v = a;
break;
}
if (a[i].first > b[i].first) {
v = b;
break;
}
}
if (v.empty()) {
v = a.size() < b.size() ? a : b;
}
for (auto i : v) {
cout << i.first << " ";
}
return 0;
}
Copy