Largest Derangement of a Sequence | C # program to find the largest derangement ; Stores result ; Insert all elements into a priority queue ; Fill Up res [ ] from left to right ; New Element poped equals the element in original sequence . Get the next largest element ; If given sequence is in descending order then we need to swap last two elements again ; Driver code
using System ; using System . Collections . Generic ; class GFG { static void printLargest ( int [ ] seq , int N ) { int [ ] res = new int [ N ] ; List < int > pq = new List < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) pq . Add ( seq [ i ] ) ; for ( int i = 0 ; i < N ; i ++ ) { pq . Sort ( ) ; pq . Reverse ( ) ; int d = pq [ 0 ] ; pq . RemoveAt ( 0 ) ; if ( d != seq [ i ] i == N - 1 ) { res [ i ] = d ; } else { res [ i ] = pq [ 0 ] ; pq . RemoveAt ( 0 ) ; pq . Add ( d ) ; } } 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 ] + " ▁ " ) ; } static void Main ( ) { int [ ] seq = { 92 , 3 , 52 , 13 , 2 , 31 , 1 } ; int n = seq . Length ; printLargest ( seq , n ) ; } }