Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | Java program to implement the above approach ; Function to check if given elements can be arranged such that sum of its neighbors 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
import java . util . * ; class GFG { static void Arrange ( int arr [ ] , int n ) { int cost = 0 ; HashMap < Integer , Integer > index = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { index . put ( arr [ i ] , i ) ; } Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) { if ( arr [ i ] > arr [ i + 1 ] + arr [ n - 1 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else if ( i == n - 1 ) { if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } else { if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) { System . out . print ( " - 1" ) ; return ; } else { cost += Math . abs ( index . get ( arr [ i ] ) - i ) ; } } } System . out . print ( cost ) ; return ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 5 , 1 , 3 } ; int N = arr . length ; Arrange ( arr , N ) ; } }