If given sequence is in descending order then we need to swap last two elements again
if ( res [ N - 1 ] == seq [ N - 1 ] ) { res [ N - 1 ] = res [ N - 2 ] ; res [ N - 2 ] = seq [ N - 1 ] ; } Console . WriteLine ( " Largest ▁ Derangement " ) ; for ( int i = 0 ; i < N ; i ++ ) Console . Write ( res [ i ] + " ▁ " ) ; }