Minimize sum of adjacent difference with removal of one element from array | C ++ implementation of above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinRemoval ( int arr [ ] , int n ) { int temp , value = 0 ; int maximum = 0 ; if ( n == 1 ) return 0 ; for ( int 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 ) ; } int main ( ) { int arr [ ] = { 1 , 5 , 3 , 2 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMinRemoval ( arr , n ) << " STRNEWLINE " ; return 0 ; }