Largest Derangement of a Sequence | Java 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
import java . io . * ; import java . util . Collections ; import java . util . PriorityQueue ; class GFG { public static void printLargest ( int a [ ] , int n ) { PriorityQueue < Integer > pq = new PriorityQueue < > ( Collections . reverseOrder ( ) ) ; int res [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { pq . add ( a [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { int p = pq . peek ( ) ; pq . remove ( ) ; if ( p != a [ i ] i == n - 1 ) { res [ i ] = p ; } else { res [ i ] = pq . peek ( ) ; pq . remove ( ) ; pq . add ( p ) ; } } 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 ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int n = 7 ; int seq [ ] = { 92 , 3 , 52 , 13 , 2 , 31 , 1 } ; printLargest ( seq , n ) ; } }