Split array into two subarrays such that difference of their sum is minimum | Python3 program for the 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 ; Given array ; Length of the array
import sys NEW_LINE def minDiffSubArray ( arr , n ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_sum += arr [ i ] NEW_LINE DEDENT prefix_sum = 0 NEW_LINE minDiff = sys . maxsize NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT prefix_sum += arr [ i ] NEW_LINE diff = abs ( ( total_sum - prefix_sum ) - prefix_sum ) NEW_LINE if ( diff < minDiff ) : NEW_LINE INDENT minDiff = diff NEW_LINE DEDENT DEDENT return minDiff NEW_LINE DEDENT arr = [ 7 , 9 , 5 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minDiffSubArray ( arr , n ) ) NEW_LINE