#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define FAST ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define mp make_pair
#define pb push_back
#define lp(i,s,f) for(ll i = s; i < ll(f); i++)
#define inF freopen("input.in", "r", stdin);
#define outF freopen("output.in", "w", stdout);
#define endl '\n'
#define MOD 1000000007
#define mm(arr) memset(arr, 0, sizeof(arr))
#define F first
#define S second
#define int ll
int32_t main(){
FAST
int n; cin >> n;
int arr[n];
bool deleted[n];
mm(deleted);
int mn = 1e9 + 5;
int ind = 0;
bool done = 0;
for(int i = 0; i < n; i++){
cin >> arr[i];
if(done)continue;
if(arr[i] <= 0){
mn = arr[i];
ind = i;
done = 1;
}
if(arr[i] < mn && i != n - 1){
mn = arr[i];
ind = i;
}
}
if(n == 1){
cout << arr[0];
return 0;
}
done = 0;
for(int i = ind + 1; i < n; i++){
if(arr[i] >= 0)done = 1;
}
int mx = 0;
int mxInd = 0;
for(int i = ind + 1; i < n; i++){
mx = max(mx, arr[i]);
if(arr[i] == mx){
mxInd = i;
}
}
for(int i = 0; i < n; i++){
if(!done && i == mxInd)continue;
if(arr[i] < 0 && i != ind){
arr[ind] += arr[i];
deleted[i] = 1;
}
}
vector<int> newarr;
for(int i = 0; i < n; i++){
if(!deleted[i]){
newarr.pb(arr[i]);
}
}
mm(deleted);
n = newarr.size();
int sufMin[n];
int indSufMin[n];
sufMin[n - 1] = newarr[n - 1];
indSufMin[n - 1] = n - 1;
for(int i = n - 2; i >= 0; i--){
sufMin[i] = min(sufMin[i + 1], newarr[i]);
if(sufMin[i] == newarr[i]){
indSufMin[i] = i;
}
else{
indSufMin[i] = indSufMin[i + 1];
}
}
int last = 0;
int sum = 0;
if(indSufMin[0] == n - 1){
int mn = 1e18 + 10;
int ind = 0;
for(int i = 0; i < n - 1; i++){
if(mn > newarr[i]){
mn = newarr[i];
ind = i;
}
}
for(int i = 0; i < ind; i++){
deleted[i] = 1;
sum += newarr[i];
}
last = ind + 1;
}
while(last != n){
for(int j = last; j <= indSufMin[last] - 1; j++){
deleted[j] = 1;
sum += newarr[j];
}
last = indSufMin[last] + 1;
}
for(int i = n - 1; i >= 1; i--){
if(!deleted[i]){
newarr[i] += sum;
break;
}
}
for(int i = n - 1; i >= 1; i--){
if(!deleted[i]){
if(newarr[i] != 0){
break;
}
else if(newarr[i] == 0){
deleted[i] = 1;
}
}
}
for(int i = 0; i < n; i++){
if(!deleted[i]){
cout << newarr[i] << " ";
}
}
return 0;
}
Copy