Split array into two subarrays such that difference of their sum is minimum | Java Program for above approach ; Function to return minimum difference between sum of two subarrays ; To store total sum of array ; Calculate the total sum of the array ; Stores the prefix sum ; Stores the minimum difference ; Traverse the given array ; To store minimum 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 total_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) total_sum += arr [ i ] ; int prefix_sum = 0 ; int minDiff = Integer . MAX_VALUE ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int diff = Math . abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; 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 ) ) ; } }