Reduce sum of same | C ++ program for the above approach ; Function to check if elements of B [ ] can be rearranged such that A [ i ] + B [ i ] <= X ; Checks the given condition ; Sort A [ ] in ascending order ; Sort B [ ] in descending order ; Traverse the arrays A [ ] and B [ ] ; If A [ i ] + B [ i ] exceeds X ; Rearrangement not possible , set flag to false ; If flag is true ; Otherwise ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrange ( int A [ ] , int B [ ] , int N , int X ) { bool flag = true ; sort ( A , A + N ) ; sort ( B , B + N , greater < int > ( ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] + B [ i ] > X ) { flag = false ; break ; } } if ( flag ) cout << " Yes " ; else cout << " No " ; } int main ( ) { int A [ ] = { 1 , 2 , 3 } ; int B [ ] = { 1 , 1 , 2 } ; int X = 4 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; rearrange ( A , B , N , X ) ; return 0 ; }