Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | C ++ program to implement the above approach ; Function to check if given elements can be arranged such that sum of its neighbours is strictly greater ; Initialize the total cost ; Storing the original index of elements in a hashmap ; Sort the given array ; Check if a given condition is satisfies or not ; First number ; Add the cost to overall cost ; Last number ; Add the cost to overall cost ; Add the cost to overall cost ; Printing the cost ; Driver Code ; Given array ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Arrange ( int arr [ ] , int n ) { int cost = 0 ; unordered_map < int , int > index ; for ( int i = 0 ; i < n ; i ++ ) { index [ arr [ i ] ] = i ; } sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] > arr [ i + 1 ] + arr [ n - 1 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } else if ( i == n - 1 ) { if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } else { if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) { cout << " - 1" ; return ; } else { cost += abs ( index [ arr [ i ] ] - i ) ; } } } cout << cost ; return ; } int main ( ) { int arr [ ] = { 2 , 4 , 5 , 1 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; Arrange ( arr , N ) ; return 0 ; }