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
function Arrange ( arr , n ) { let cost = 0 ; let index = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { index . set ( arr [ i ] , i ) } arr . sort ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] > arr [ i + 1 ] + arr [ n - 1 ] ) { document . write ( " " ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else if ( i == n - 1 ) { if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) { document . write ( " " ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else { if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) { document . write ( " " ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } } document . write ( cost ) ; return ; } let arr = [ 2 , 4 , 5 , 1 , 3 ] ; let N = arr . length ; Arrange ( arr , N ) ;