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