#include<bits/stdc++.h>
typedef long long ll;
typedef long l;

using namespace std;

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);  cout.tie(0);
    ll n;
    cin >> n;
    int*a = new int[n];
    for(ll i=0; i<n; i++)
        cin >> a[i];
    ll nc = -1;
    ll nci = -1;
    ll l_i = -1;
    ll r_i = -1;

    for (ll i=n-1; i>=0; i--)
    {
        if (a[i]>nc)
        {
            nc = a[i];
            nci = i;
            continue;
        }

        if (a[i]<nc)
        {
            l_i = i;
            r_i = nci;
        }
    }

    if (l_i==-1)
    {
       unordered_set <int> s;
       for (ll i = 0; i < n; i++) s.insert(a[i]);
       if(n==s.size()) swap(a[n-2],a[n-1]);
    }

    else swap(a[l_i],a[r_i]);
    for(ll i=0; i<n; i++) cout << a[i] << " ";



    return 0;
}