Rearrange array such that sum of same indexed elements is atmost K | Java program for the above approach ; Reverse array ; Function to rearrange array such that sum of similar indexed elements does not exceed K ; Sort the array B [ ] in descending order ; If condition fails ; Print the array ; Driver Code ; Given arrays
import java . util . * ; class GFG { static int [ ] reverse ( int a [ ] ) { int i , n = a . length , t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static void rearrangeArray ( int A [ ] , int B [ ] , int N , int K ) { Arrays . sort ( B ) ; B = reverse ( B ) ; boolean flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] + B [ i ] > K ) { flag = false ; break ; } } if ( ! flag ) { System . out . print ( " - 1" + "NEW_LINE"); } else { for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( B [ i ] + " ▁ " ) ; } } } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 3 , 4 , 2 } ; int B [ ] = { 1 , 2 , 3 , 1 , 1 } ; int N = A . length ; int K = 5 ; rearrangeArray ( A , B , N , K ) ; } }