Rearrange an Array such that Sum of same | Java program to implement the above approach ; Function to rearrange the array such that no same - indexed subset have sum equal to that in the original array ; Initialize a vector ; Iterate the array ; Sort the vector ; Shift of elements to the index of its next cyclic element ; Print the answer ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static class pair { int first , second ; pair ( int first , int second ) { this . first = first ; this . second = second ; } } static void printNewArray ( List < Integer > a , int n ) { List < pair > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { v . add ( new pair ( a . get ( i ) , i ) ) ; } Collections . sort ( v , ( pair s1 , pair s2 ) -> { return s1 . first - s2 . first ; } ) ; int ans [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { ans [ v . get ( ( i + 1 ) % n ) . second ] = v . get ( i ) . first ; } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String args [ ] ) { List < Integer > a = Arrays . asList ( 4 , 1 , 2 , 5 , 3 ) ; int n = a . size ( ) ; printNewArray ( a , n ) ; } }