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
< ? php function findMinRemoval ( $ arr , $ n ) { $ value = 0 ; $ maximum = 0 ; if ( $ n == 1 ) return 0 ; $ temp = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i != 0 && $ i != $ n - 1 ) { $ value = $ value + abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) + abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) - abs ( $ arr [ $ i - 1 ] - $ arr [ $ i + 1 ] ) ; } else if ( $ i == 0 ) { $ value = $ value + abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; } else $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) ; $ maximum = max ( $ maximum , $ temp ) ; } return ( $ value - $ maximum ) ; } $ arr = array ( 1 , 5 , 3 , 2 , 10 ) ; $ n = count ( $ arr ) ; echo findMinRemoval ( $ arr , $ n ) ; ? >