Modify array to maximize sum of adjacent differences | Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ; for [ i + 1 ] [ 1 ] ( i . e . current modified value is arr [ i + 1 ] ) , choose maximum from dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) and dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ; Driver Code
def maximumDifferenceSum ( arr , N ) : NEW_LINE INDENT dp = [ [ 0 , 0 ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i ] [ 1 ] = 0 NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] , dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ) NEW_LINE dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) , dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ) NEW_LINE DEDENT return max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumDifferenceSum ( arr , N ) ) NEW_LINE DEDENT