Dividing an array into two halves of same sum

2.6

Given an even size array of integers. We need to find if it is possible to divide array elements into two sets such that following conditions are true.

  1. Size of both subsets is same.
  2. Sum of elements in bot sets is same.
  3. Every element is part of one of the two sets.

Examples :

Input: arr[] = {1, 3, 2, 1, 2, 1}
Output : Yes
Explanation: We can get two subsets
as {1, 3, 1} and {2, 2, 1}

Input: {1, 2, 3, 4, 5, 6}
Output : No

The idea is based on method 1 of following post.
Print all possible combinations of r elements in a given array of size n

We generate all subsets of size n/2. For every subset, we check if its sum is total sum by 2.

C++

// Program to check if we can divide an array into two
// halves such that sum of the two is same.
#include <bits/stdc++.h>
using namespace std;

bool combinationUtil(int arr[], int half[], int start, int end,
                     int index, int n, int sum);

// Returns true if it is possible to divide array into two halves.
// of same sum. This function mainly uses combinationUtil()
bool isPossible(int arr[], int n)
{
    // If size of array is not even.
    if (n % 2 != 0)
        return false;

    // If sum of array is not even.
    int sum = accumulate(arr, arr + n, 0);
    if (sum % 2 != 0)
        return false;

    // A temporary array to store all combination one by one
    int half[n / 2];

    // Print all combination using temporary array 'half[]'
    return combinationUtil(arr, half, 0, n - 1, 0, n, sum);
}

/* arr[] ---> Input Array
   half[] ---> Temporary array to store current combination
               of size n/2
   start & end ---> Staring and Ending indexes in arr[]
   index ---> Current index in half[] */
bool combinationUtil(int arr[], int half[], int start, int end,
                     int index, int n, int sum)
{
    // Current combination is ready to be printed, print it
    if (index == n / 2) {
        int curr_sum = accumulate(half, half + n / 2, 0);
        return (curr_sum + curr_sum == sum);
    }

    // replace index with all possible elements. The condition
    // "end-i+1 >= n/2-index" makes sure that including one element
    // at index will make a combination with remaining elements
    // at remaining positions
    for (int i = start; i <= end && end - i + 1 >= n/2 - index; i++) {
        half[index] = arr[i];
        if (combinationUtil(arr, half, i + 1, end, index + 1, n, sum))
            return true;
    }

    return false;
}

// Driver program to test above functions
int main()
{
    int arr[] = { 1, 2, 4, 4, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    if (isPossible(arr, n))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}

Java

// Java program to check if we can
// divide an array into two halves
// such that sum of the two is same.
public class DivideArray{ 
    
    static int accumulate(int arr[], int first,
                                     int last)
    {
        int init = 0;
        for (int i = first; i< last; i++) {
            init = init + arr[i];
        }
    
        return init;
    }

    // Returns true if it is possible to divide 
    // array into two halves of same sum. 
    // This function mainly uses combinationUtil()
    static Boolean isPossible(int arr[], int n)
    {
        // If size of array is not even.
        if (n % 2 != 0)
            return false;

        // If sum of array is not even.
        int sum = accumulate(arr, 0, n);
        if (sum % 2 != 0)
            return false;

        // A temporary array to store all 
        // combination one by one int k=n/2;
        int half[] = new int[n/2];

        // Print all combination using temporary
        // array 'half[]'
        return combinationUtil(arr, half, 0, n - 1,
                                0, n, sum);
    }

    /* arr[] ---> Input Array
    half[] ---> Temporary array to store current 
                combination of size n/2
    start & end ---> Staring and Ending indexes in arr[]
    index ---> Current index in half[] */
    static Boolean combinationUtil(int arr[], int half[], 
                                   int start, int end,
                                   int index, int n,
                                   int sum)
    {
        // Current combination is ready to 
        // be printed, print it
        if (index == n / 2) {
            int curr_sum = accumulate(half, 0 , n/2);
            return (curr_sum + curr_sum == sum);
        }

        // replace index with all possible elements. 
        // The condition "end-i+1 >= n/2-index" makes
        // sure that including one element at index 
        // will make a combination with remaining
        // elements at remaining positions
        for (int i = start; i <= end && end - i + 1 >= 
                                  n/2 - index; i++) {
            half[index] = arr[i];
            if (combinationUtil(arr, half, i + 1, end, 
                                 index + 1, n, sum))
                return true;
        }

        return false;
    }

    // Driver code
    public static void main(String[] s)
    {
        int arr[] = {1, 2, 4, 4, 5, 6 };
        
        if (isPossible(arr, arr.length))
        System.out.println("Yes");
        else
        System.out.println("NO");
    }
}

// This code is contributed by Prerna Saini


Output:

Yes

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2.6 Average Difficulty : 2.6/5.0
Based on 3 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.