Split given arrays into subarrays to maximize the sum of maximum and minimum in each subarrays | Java program for the above approach ; 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
import java . io . * ; class GFG { static int maxDiffSum ( int [ ] arr , int n ) { int [ ] dp = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { int maxVal = arr [ i ] , minVal = arr [ i ] ; for ( int 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 ] ; } public static void main ( String [ ] args ) { int [ ] arr = { 8 , 1 , 7 , 9 , 2 } ; int N = arr . length ; System . out . print ( maxDiffSum ( arr , N ) ) ; } }