#include <iostream>
using namespace std;

long long n;
int a[10000000];
int b[10000000];

void razmeni(int *a, int *b){
	int t;
	t = *a;
	*a = *b;
	*b = t;
}


void max(long long n, int a[]){
	
	long long m = n - 1;
	b [n-1] = -1;
	
	for(long long i = n-2; i >= 0; i--){
		if(a[i] < a[m]){
			b[i] = m;
		}
		else{
			b[i] = -1;
			m = i;
		}
	}
	for(long long i = 0; i < n; i++){
		if(b[i]!=-1){
			razmeni(&a[i], &a[b[i]]);break;
		}
	}
}

bool opadajuci(long long n, int a[]){
	for(long long i = 1; i < n; i++) if( a[i] > a[i-1] )return false;
	return true;
}





int main(){
	ios_base::sync_with_stdio(false);
	cin >> n;
	for(long long i = 0; i<n; i++){
		cin >> a[i];
	}
	if(opadajuci(n, a)){
		razmeni(&a[n-1], &a[n-2]);
		for(long long i = 0; i<n; i++){
		cout << a[i] << " ";
		}
	}
	else{
		max(n,a);
		for(long long i = 0; i<n; i++){
		cout << a[i] << " ";
		}
	}
	
	
	
	
	
	
	return 0;
}