Split array into two subarrays such that difference of their sum is minimum | 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 ; Given array ; Length of the array
function minDiffSubArray ( arr , n ) { var total_sum = 0 ; for ( var i = 0 ; i < n ; i ++ ) total_sum += arr [ i ] ; var prefix_sum = 0 ; var minDiff = 1000000000 ; for ( var i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; var diff = Math . abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } var arr = [ 7 , 9 , 5 , 10 ] ; var n = arr . length ; document . write ( minDiffSubArray ( arr , n ) ) ;