text: Rearrange array such that sum of same indexed elements is atmost K | C ++ program for the above approach ; 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeArray ( int A [ ] , int B [ ] , int N , int K ) { sort ( B , B + N , greater < int > ( ) ) ; bool flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] + B [ i ] > K ) { flag = false ; break ; } } if ( ! flag ) { cout << " - 1" << endl ; } else { for ( int i = 0 ; i < N ; i ++ ) { cout << B [ i ] << " ▁ " ; } } } int main ( ) { int A [ ] = { 1 , 2 , 3 , 4 , 2 } ; int B [ ] = { 1 , 2 , 3 , 1 , 1 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; int K = 5 ; rearrangeArray ( A , B , N , K ) ; return 0 ; }