#include <bits/stdc++.h>

using namespace std;

int a[1000005]={0};

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>a[i];
    }

    int msf=-1;
    int mInd=-1;
    int indP=-1;
    int indK=-1;

    for(int i=n-1;i>=0;i--){
        if(a[i]>msf){
            msf=a[i];
            mInd=i;
        }
        else{
            if(msf>a[i]){
                indK=i;
                indP=mInd;
            }
            else if(indK==-1&&msf==a[i]){
                indK=i;
                indP=mInd;
            }
        }
    }
    if(indK!=-1){
        int pom=a[indP];
        a[indP]=a[indK];
        a[indK]=pom;
    }
    else{
        int pom=a[n-1];
        a[n-1]=a[n-2];
        a[n-2]=pom;
    }
    for(int i=0;i<n;i++){
        cout<<a[i]<<" ";
    }
    return 0;
}