Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | Function to find the maximum sum of differences of subarrays by splitting array into non - overlapping subarrays ; Stores the answer for prefix and initialize with zero ; Assume i - th index as right endpoint ; Choose the current value as the maximum and minimum ; Find the left endpoint and update the array dp [ ] ; Return answer ; Driver Code
function maxDiffSum ( arr , n ) { let dp = new Array ( n ) . fill ( 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { let maxVal = arr [ i ] , minVal = arr [ i ] ; for ( let j = i ; j >= 0 ; j -- ) { minVal = Math . min ( minVal , arr [ j ] ) ; maxVal = Math . max ( maxVal , arr [ j ] ) ; if ( j - 1 >= 0 ) dp [ i ] = Math . max ( dp [ i ] , maxVal - minVal + dp [ j - 1 ] ) ; else dp [ i ] = Math . max ( dp [ i ] , maxVal - minVal ) ; } } return dp [ n - 1 ] ; } let arr = [ 8 , 1 , 7 , 9 , 2 ] ; let N = arr . length ; document . write ( maxDiffSum ( arr , N ) ) ;