Split array into two subarrays such that difference of their sum is minimum

27 May, 2021
Given an integer array arr[], the task is to split the given array into two subarrays such that the difference between their sum is minimum.
Examples:
Input: arr[] = {7, 9, 5, 10}Output: 1Explanation: The difference between the sum of the subarrays {7, 9} and {5, 10} is equal to [16 – 15] = 1, which is the minimum possible.
Input: arr[] = {6, 6, 6}Output: 6
Naive Approach: The idea is to use the Prefix and Suffix Sum array technique. Generate the prefix sum array and the suffix sum array of the given array. Now, iterate over the array and print the minimum difference between prefix_sum[i] and suffix_sum[i+1], for any index i ( 0 <= i <= N – 1) from the array.Time Complexity: O(N)Auxiliary Space: O(N)
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum difference// between two subarray sumsint minDiffSubArray(int arr[], int n){     // To store prefix sums    int prefix_sum[n];     // Generate prefix sum array    prefix_sum[0] = arr[0];     for(int i = 1; i < n; i++)        prefix_sum[i] = prefix_sum[i - 1] +                               arr[i];     // To store suffix sums    int suffix_sum[n];     // Generate suffix sum array    suffix_sum[n - 1] = arr[n - 1];     for(int i = n - 2; i >= 0; i--)        suffix_sum[i] = suffix_sum[i + 1] +                               arr[i];     // Stores the minimum difference    int minDiff = INT_MAX;     // Traverse the given array    for(int i = 0; i < n - 1; i++)    {                 // Calculate the difference        int diff = abs(prefix_sum[i] -                       suffix_sum[i + 1]);         // Update minDiff        if (diff < minDiff)            minDiff = diff;    }     // Return minDiff    return minDiff;} // Driver Codeint main(){         // Given array    int arr[] = { 7, 9, 5, 10 };     // Length of the array    int n = sizeof(arr) / sizeof(arr[0]);     cout << minDiffSubArray(arr, n);} // This code is contributed by code_hunt
// Java Program for above approachimport java.util.*;import java.lang.*; class GFG {     // Function to return minimum difference    // between two subarray sums    static int minDiffSubArray(int arr[], int n)    {         // To store prefix sums        int[] prefix_sum = new int[n];         // Generate prefix sum array        prefix_sum[0] = arr[0];         for (int i = 1; i < n; i++)            prefix_sum[i]                = prefix_sum[i - 1] + arr[i];         // To store suffix sums        int[] suffix_sum = new int[n];         // Generate suffix sum array        suffix_sum[n - 1] = arr[n - 1];         for (int i = n - 2; i >= 0; i--)            suffix_sum[i]                = suffix_sum[i + 1] + arr[i];         // Stores the minimum difference        int minDiff = Integer.MAX_VALUE;         // Traverse the given array        for (int i = 0; i < n - 1; i++) {             // Calculate the difference            int diff                = Math.abs(prefix_sum[i]                           - suffix_sum[i + 1]);             // Update minDiff            if (diff < minDiff)                minDiff = diff;        }         // Return minDiff        return minDiff;    }     // Driver Code    public static void main(String[] args)    {        // Given array        int[] arr = { 7, 9, 5, 10 };         // Length of the array        int n = arr.length;         System.out.println(            minDiffSubArray(arr, n));    }}
# Python3 program for the above approachimport sys # Function to return minimum difference# between two subarray sumsdef minDiffSubArray(arr, n):     # To store prefix sums    prefix_sum = [0] * n     # Generate prefix sum array    prefix_sum[0] = arr[0]     for i in range(1, n):        prefix_sum[i] = (prefix_sum[i - 1] +                                arr[i])     # To store suffix sums    suffix_sum = [0] * n     # Generate suffix sum array    suffix_sum[n - 1] = arr[n - 1]     for i in range(n - 2, -1, -1):        suffix_sum[i] = (suffix_sum[i + 1] +                                arr[i])     # Stores the minimum difference    minDiff = sys.maxsize     # Traverse the given array    for i in range(n - 1):         # Calculate the difference        diff = abs(prefix_sum[i] -                   suffix_sum[i + 1])         # Update minDiff        if (diff < minDiff):            minDiff = diff     # Return minDiff    return minDiff # Driver Codeif __name__ == '__main__':         # Given array    arr = [ 7, 9, 5, 10 ]     # Length of the array    n = len(arr)     print(minDiffSubArray(arr, n)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;class GFG{ // Function to return minimum difference// between two subarray sumsstatic int minDiffSubArray(int []arr,                           int n){     // To store prefix sums  int[] prefix_sum = new int[n];   // Generate prefix sum array  prefix_sum[0] = arr[0];   for(int i = 1; i < n; i++)    prefix_sum[i] = prefix_sum[i - 1] +                    arr[i];   // To store suffix sums  int[] suffix_sum = new int[n];   // Generate suffix sum array  suffix_sum[n - 1] = arr[n - 1];   for(int i = n - 2; i >= 0; i--)    suffix_sum[i] = suffix_sum[i + 1] +                    arr[i];   // Stores the minimum difference  int minDiff = int.MaxValue;   // Traverse the given array  for(int i = 0; i < n - 1; i++)  {    // Calculate the difference    int diff = Math.Abs(prefix_sum[i] -                        suffix_sum[i + 1]);     // Update minDiff    if (diff < minDiff)      minDiff = diff;    }     // Return minDiff    return minDiff;} // Driver Codepublic static void Main(String[] args){       // Given array    int[] arr = {7, 9, 5, 10};     // Length of the array    int n = arr.Length;     Console.WriteLine(minDiffSubArray(arr, n));}} // This code is contributed by Amit Katiyar
<script>    // Javascript program for the above approach         // Function to return minimum difference    // between two subarray sums    function minDiffSubArray(arr, n)    {        // To store prefix sums      let prefix_sum = new Array(n);       // Generate prefix sum array      prefix_sum[0] = arr[0];       for(let i = 1; i < n; i++)        prefix_sum[i] = prefix_sum[i - 1] + arr[i];       // To store suffix sums      let suffix_sum = new Array(n);       // Generate suffix sum array      suffix_sum[n - 1] = arr[n - 1];       for(let i = n - 2; i >= 0; i--)        suffix_sum[i] = suffix_sum[i + 1] + arr[i];       // Stores the minimum difference      let minDiff = Number.MAX_VALUE;       // Traverse the given array      for(let i = 0; i < n - 1; i++)      {        // Calculate the difference        let diff = Math.abs(prefix_sum[i] - suffix_sum[i + 1]);         // Update minDiff        if (diff < minDiff)          minDiff = diff;        }         // Return minDiff        return minDiff;    }         // Given array    let arr = [7, 9, 5, 10];      // Length of the array    let n = arr.length;      document.write(minDiffSubArray(arr, n)); // This code is contributed by vaibhavrabadiya117.</script>
  
1
 
Efficient Approach: To optimize the above approach, the idea is to calculate the total sum of the array elements. Now, iterate over the array and calculate the prefix sum of the array and find the minimum difference between the prefix sum and the difference between total sum and the prefix sum for any index of the array, i.e.,
 
Maximum difference between sum of subarrays = ( prefix_sum – (total_sum – prefix_sum) )
 
Below is the implementation of the above approach:
 
C++
Java
Python3
C#
Javascript
// C++ program for above approach#include <bits/stdc++.h>using namespace std; // Function to return minimum difference// between sum of two subarraysint minDiffSubArray(int arr[], int n){         // To store total sum of array    int total_sum = 0;     // Calculate the total sum    // of the array    for(int i = 0; i < n; i++)        total_sum += arr[i];     // Stores the prefix sum    int prefix_sum = 0;     // Stores the minimum difference    int minDiff = INT_MAX;     // Traverse the given array    for(int i = 0; i < n - 1; i++)    {        prefix_sum += arr[i];         // To store minimum difference        int diff = abs((total_sum -                       prefix_sum) -                       prefix_sum);         // Update minDiff        if (diff < minDiff)            minDiff = diff;    }     // Return minDiff    return minDiff;} // Driver codeint main(){         // Given array    int arr[] = { 7, 9, 5, 10 };     // Length of the array    int n = sizeof(arr) / sizeof(arr[0]);     cout << minDiffSubArray(arr, n) << endl;     return 0;} // This code is contributed by divyeshrabadiya07
// Java Program for above approachimport java.util.*;import java.lang.*; class GFG {     // Function to return minimum difference    // between sum of two subarrays    static int minDiffSubArray(int arr[], int n)    {        // To store total sum of array        int total_sum = 0;         // Calculate the total sum        // of the array        for (int i = 0; i < n; i++)            total_sum += arr[i];         // Stores the prefix sum        int prefix_sum = 0;         // Stores the minimum difference        int minDiff = Integer.MAX_VALUE;         // Traverse the given array        for (int i = 0; i < n - 1; i++) {             prefix_sum += arr[i];             // To store minimum difference            int diff                = Math.abs((total_sum                            - prefix_sum)                           - prefix_sum);             // Update minDiff            if (diff < minDiff)                minDiff = diff;        }         // Return minDiff        return minDiff;    }     // Driver Code    public static void main(String[] args)    {        // Given array        int[] arr = { 7, 9, 5, 10 };         // Length of the array        int n = arr.length;         System.out.println(            minDiffSubArray(arr, n));    }}
# Python3 program for the above approachimport sys # Function to return minimum difference# between sum of two subarraysdef minDiffSubArray(arr, n):         # To store total sum of array    total_sum = 0     # Calculate the total sum    # of the array    for i in range(n):        total_sum += arr[i]     # Stores the prefix sum    prefix_sum = 0     # Stores the minimum difference    minDiff = sys.maxsize     # Traverse the given array    for i in range(n - 1):        prefix_sum += arr[i]         # To store minimum difference        diff = abs((total_sum -                   prefix_sum) -                   prefix_sum)         # Update minDiff        if (diff < minDiff):            minDiff = diff     # Return minDiff    return minDiff # Driver code     # Given arrayarr = [ 7, 9, 5, 10 ] # Length of the arrayn = len(arr) print(minDiffSubArray(arr, n)) # This code is contributed by code_hunt
// C# Program for above approachusing System;class GFG{ // Function to return minimum difference// between sum of two subarraysstatic int minDiffSubArray(int []arr,                           int n){  // To store total sum of array  int total_sum = 0;   // Calculate the total sum  // of the array  for (int i = 0; i < n; i++)    total_sum += arr[i];   // Stores the prefix sum  int prefix_sum = 0;   // Stores the minimum difference  int minDiff = int.MaxValue;   // Traverse the given array  for (int i = 0; i < n - 1; i++)  {    prefix_sum += arr[i];     // To store minimum difference    int diff = Math.Abs((total_sum -                         prefix_sum) -                         prefix_sum);     // Update minDiff    if (diff < minDiff)      minDiff = diff;  }   // Return minDiff  return minDiff;} // Driver Codepublic static void Main(String[] args){  // Given array  int[] arr = {7, 9, 5, 10};   // Length of the array  int n = arr.Length;   Console.WriteLine(          minDiffSubArray(arr, n));}} // This code is contributed by Rajput-Ji
<script> // Javascript program for above approach // Function to return minimum difference// between sum of two subarraysfunction minDiffSubArray(arr, n){         // To store total sum of array    var total_sum = 0;     // Calculate the total sum    // of the array    for(var i = 0; i < n; i++)        total_sum += arr[i];     // Stores the prefix sum    var prefix_sum = 0;     // Stores the minimum difference    var minDiff = 1000000000;     // Traverse the given array    for(var i = 0; i < n - 1; i++)    {        prefix_sum += arr[i];         // To store minimum difference        var diff = Math.abs((total_sum -                       prefix_sum) -                       prefix_sum);         // Update minDiff        if (diff < minDiff)            minDiff = diff;    }     // Return minDiff    return minDiff;} // Driver code// Given arrayvar arr = [7, 9, 5, 10]; // Length of the arrayvar n = arr.length;document.write( minDiffSubArray(arr, n)); // This code is contributed by importantly.</script>
1
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
amit143katiyar
Rajput-Ji
divyeshrabadiya07
code_hunt
importantly
vaibhavrabadiya117
prefix-sum
subarray
Suffix
Arrays
Mathematical
Searching
prefix-sum
Arrays
Searching
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Longest Consecutive Subsequence
Chocolate Distribution Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7