Find the left endpoint and update the array dp [ ]
for ( int j = i ; j >= 0 ; j -- ) { minVal = min ( minVal , arr [ j ] ) ; maxVal = max ( maxVal , arr [ j ] ) ; if ( j - 1 >= 0 ) dp [ i ] = max ( dp [ i ] , maxVal - minVal + dp [ j - 1 ] ) ; else dp [ i ] = max ( dp [ i ] , maxVal - minVal ) ; } }