Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements | C ++ implementation of the approach ; Function to print the arrangement that satisifes the given condition ; Sort the array initially ; Array that stores the arrangement ; Once the array is sorted Re - fill the array again in the mentioned way in the approach ; Iterate in the array and check if the arrangement made satisfies the given condition or not ; For the first element the adjacents will be a [ 1 ] and a [ n - 1 ] ; For the last element the adjacents will be a [ 0 ] and a [ n - 2 ] ; If we reach this position then the arrangement is possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printArrangement ( int a [ ] , int n ) { sort ( a , a + n ) ; int b [ n ] ; int low = 0 , high = n - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) b [ low ++ ] = a [ i ] ; else b [ high -- ] = a [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( b [ n - 1 ] + b [ 1 ] <= b [ i ] ) { cout << -1 ; return ; } } else if ( i == ( n - 1 ) ) { if ( b [ n - 2 ] + b [ 0 ] <= b [ i ] ) { cout << -1 ; return ; } } else { if ( b [ i - 1 ] + b [ i + 1 ] <= b [ i ] ) { cout << -1 ; return ; } } } for ( int i = 0 ; i < n ; i ++ ) cout << b [ i ] << " ▁ " ; } int main ( ) { int a [ ] = { 1 , 4 , 4 , 3 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; printArrangement ( a , n ) ; return 0 ; }