Minimize sum of adjacent difference with removal of one element from array | Function to find the element ; Value variable for storing the total value ; Declaring maximum value as zero ; If array contains on element ; Storing the maximum value in temp variable ; Adding the adjacent difference modulus values of removed element . Removing adjacent difference modulus value after removing element ; Returning total value - maximum value ; Drivers code
function findMinRemoval ( arr , n ) { var temp , value = 0 ; var maximum = 0 ; if ( n == 1 ) return 0 ; for ( var i = 0 ; i < n ; i ++ ) { if ( i != 0 && i != n - 1 ) { value = value + Math . abs ( arr [ i ] - arr [ i + 1 ] ) ; temp = Math . abs ( arr [ i ] - arr [ i + 1 ] ) + Math . abs ( arr [ i ] - arr [ i - 1 ] ) - Math . abs ( arr [ i - 1 ] - arr [ i + 1 ] ) ; } else if ( i == 0 ) { value = value + Math . abs ( arr [ i ] - arr [ i + 1 ] ) ; temp = Math . abs ( arr [ i ] - arr [ i + 1 ] ) ; } else temp = Math . abs ( arr [ i ] - arr [ i - 1 ] ) ; maximum = Math . max ( maximum , temp ) ; } return ( value - maximum ) ; } var arr = [ 1 , 5 , 3 , 2 , 10 ] ; var n = arr . length ; document . write ( findMinRemoval ( arr , n ) + " " ) ;