If given sequence is in descending order then we need to swap last two elements again
if ( res [ n - 1 ] == a [ n - 1 ] ) { res [ n - 1 ] = res [ n - 2 ] ; res [ n - 2 ] = a [ n - 1 ] ; } System . out . println ( " Largest ▁ Derangement " ) ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( res [ i ] + " ▁ " ) ; } }