Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimally divide an array into two subarrays so that sum of elements in both are same, otherwise give an error?

How to optimally divide an array into two subarrays so that sum of elements in both subarrays is same, otherwise give an error?

Example 1

Given the array

10,  20 , 30 , 5 , 40 , 50 , 40 , 15 

It can be divided as

10, 20, 30, 5, 40 

and

50, 40, 15 

Each subarray sums up to 105.

Example 2

10,  20,  30,  5,  40,  50,  40,  10 

The array cannot be divided into 2 arrays of an equal sum.

like image 781
Samarth2011 Avatar asked May 05 '11 13:05

Samarth2011


People also ask

How do you divide an array into subarrays of equal sum?

A Simple solution is to run two loop to split array and check it is possible to split array into two parts such that sum of first_part equal to sum of second_part. Below is the implementation of above idea.

How do you divide an array into parts?

Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.

How many Subarrays can be formed from an array?

The total number of subarrays in an array of size N is N * (N + 1) / 2. The count of subarrays with an odd product is equal to the total number of continuous odd elements present in the array.


1 Answers

There exists a solution, which involves dynamic programming, that runs in O(n*TotalSum), where n is the number of elements in the array and TotalSum is their total sum.

The first part consists in calculating the set of all numbers that can be created by adding elements to the array.

For an array of size n, we will call this T(n),

T(n) = T(n-1) UNION { Array[n]+k | k is in T(n-1) } 

(The proof of correctness is by induction, as in most cases of recursive functions.)

Also, remember for each cell in the dynamic matrix, the elements that were added in order to create it.

Simple complexity analysis will show that this is done in O(n*TotalSum).

After calculating T(n), search the set for an element exactly the size of TotalSum / 2.

If such an item exists, then the elements that created it, added together, equal TotalSum / 2, and the elements that were not part of its creation also equal TotalSum / 2 (TotalSum - TotalSum / 2 = TotalSum / 2).

This is a pseudo-polynomial solution. AFAIK, this problem is not known to be in P.

like image 71
Gal Avatar answered Sep 24 '22 13:09

Gal