Skip to content
Related Articles

Related Articles

Split array into two subarrays such that difference of their sum is minimum
  • Difficulty Level : Medium
  • Last Updated : 18 Sep, 2020

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: 1
Explanation: 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h> 
using namespace std; 
  
// Function to return minimum difference
// between two subarray sums
int 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 Code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for above approach
import 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
  
# Function to return minimum difference
# between two subarray sums
def 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 Code
if __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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
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 = 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 Code
public 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

chevron_right


Output: 

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return minimum difference
// between sum of two subarrays
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_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 code
int 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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for above approach
import 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the above approach
import sys
  
# Function to return minimum difference
# between sum of two subarrays
def 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 array
arr = [ 7, 9, 5, 10 ]
  
# Length of the array
n = len(arr) 
  
print(minDiffSubArray(arr, n))
  
# This code is contributed by code_hunt

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# Program for above approach
using System;
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 = 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 Code
public 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

chevron_right


Output: 

1

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :