Split array into two subarrays such that difference of their sum is minimum | Java Program for above approach ; Function to return minimum difference between two subarray sums ; To store prefix sums ; Generate prefix sum array ; To store suffix sums ; Generate suffix sum array ; Stores the minimum difference ; Traverse the given array ; Calculate the difference ; Update minDiff ; Return minDiff ; Driver Code ; Given array ; Length of the array
import java . util . * ; import java . lang . * ; class GFG { static int minDiffSubArray ( int arr [ ] , int n ) { int [ ] prefix_sum = new int [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; int [ ] suffix_sum = new int [ n ] ; suffix_sum [ n - 1 ] = arr [ n - 1 ] ; for ( int i = n - 2 ; i >= 0 ; i -- ) suffix_sum [ i ] = suffix_sum [ i + 1 ] + arr [ i ] ; int minDiff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { int diff = Math . abs ( prefix_sum [ i ] - suffix_sum [ i + 1 ] ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 9 , 5 , 10 } ; int n = arr . length ; System . out . println ( minDiffSubArray ( arr , n ) ) ; } }