Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | 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 ; Given array ; Function call
def Arrange ( arr , n ) : NEW_LINE INDENT cost = 0 NEW_LINE index = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT index [ arr [ i ] ] = i NEW_LINE DEDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] + arr [ - 1 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT elif ( i == n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT DEDENT print ( cost ) NEW_LINE return NEW_LINE DEDENT arr = [ 2 , 4 , 5 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE Arrange ( arr , N ) NEW_LINE