Split array into two subarrays such that difference of their sum is minimum | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 = INT_MAX ; for ( int i = 0 ; i < n - 1 ; i ++ ) { prefix_sum += arr [ i ] ; int diff = abs ( ( total_sum - prefix_sum ) - prefix_sum ) ; if ( diff < minDiff ) minDiff = diff ; } return minDiff ; } int main ( ) { int arr [ ] = { 7 , 9 , 5 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minDiffSubArray ( arr , n ) << endl ; return 0 ; }