Dynamic Programming | Set 18 (Partition problem)
Partition problem is to determine whether a given set can be partitioned into two subsets such that the sum of elements in both subsets is same.
Examples
arr[] = {1, 5, 11, 5}
Output: true
The array can be partitioned as {1, 5, 5} and {11}
arr[] = {1, 5, 3}
Output: false
The array cannot be partitioned into equal sum sets.
Following are the two main steps to solve this problem:
1) Calculate sum of the array. If sum is odd, there can not be two subsets with equal sum, so return false.
2) If sum of array elements is even, calculate sum/2 and find a subset of array with sum equal to sum/2.
The first step is simple. The second step is crucial, it can be solved either using recursion or Dynamic Programming.
Recursive Solution
Following is the recursive property of the second step mentioned above.
Let isSubsetSum(arr, n, sum/2) be the function that returns true if
there is a subset of arr[0..n-1] with sum equal to sum/2
The isSubsetSum problem can be divided into two subproblems
a) isSubsetSum() without considering last element
(reducing n to n-1)
b) isSubsetSum considering the last element
(reducing sum/2 by arr[n-1] and n to n-1)
If any of the above the above subproblems return true, then return true.
isSubsetSum (arr, n, sum/2) = isSubsetSum (arr, n-1, sum/2) ||
isSubsetSum (arr, n-1, sum/2 - arr[n-1])
// A recursive solution for partition problem
#include <stdio.h>
// A utility function that returns true if there is a subset of arr[]
// with sun equal to given sum
bool isSubsetSum (int arr[], int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element
*/
return isSubsetSum (arr, n-1, sum) || isSubsetSum (arr, n-1, sum-arr[n-1]);
}
// Returns true if arr[] can be partitioned in two subsets of
// equal sum, otherwise false
bool findPartiion (int arr[], int n)
{
// Calculate sum of the elements in array
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// If sum is odd, there cannot be two subsets with equal sum
if (sum%2 != 0)
return false;
// Find if there is subset with sum equal to half of total sum
return isSubsetSum (arr, n, sum/2);
}
// Driver program to test above function
int main()
{
int arr[] = {3, 1, 5, 9, 12};
int n = sizeof(arr)/sizeof(arr[0]);
if (findPartiion(arr, n) == true)
printf("Can be divided into two subsets of equal sum");
else
printf("Can not be divided into two subsets of equal sum");
getchar();
return 0;
}
Output:
Can be divided into two subsets of equal sum
Time Complexity: O(2^n) In worst case, this solution tries two possibilities (whether to include or exclude) for every element.
Dynamic Programming Solution
The problem can be solved using dynamic programming when the sum of the elements is not too big. We can create a 2D array part[][] of size (sum/2)*(n+1). And we can construct the solution in bottom up manner such that every filled entry has following property
part[i][j] = true if a subset of {arr[0], arr[1], ..arr[j-1]} has sum
equal to i, otherwise false
// A Dynamic Programming solution to partition problem
#include <stdio.h>
// Returns true if arr[] can be partitioned in two subsets of
// equal sum, otherwise false
bool findPartiion (int arr[], int n)
{
int sum = 0;
int i, j;
// Caculcate sun of all elements
for (i = 0; i < n; i++)
sum += arr[i];
if (sum%2 != 0)
return false;
bool part[sum/2+1][n+1];
// initialize top row as true
for (i = 0; i <= n; i++)
part[0][i] = true;
// initialize leftmost column, except part[0][0], as 0
for (i = 1; i <= sum/2; i++)
part[i][0] = false;
// Fill the partition table in botton up manner
for (i = 1; i <= sum/2; i++)
{
for (j = 1; j <= n; j++)
{
part[i][j] = part[i][j-1];
if (i >= arr[j-1])
part[i][j] = part[i][j] || part[i - arr[j-1]][j-1];
}
}
/* // uncomment this part to print table
for (i = 0; i <= sum/2; i++)
{
for (j = 0; j <= n; j++)
printf ("%4d", part[i][j]);
printf("\n");
} */
return part[sum/2][n];
}
// Driver program to test above funtion
int main()
{
int arr[] = {3, 1, 1, 2, 2, 1};
int n = sizeof(arr)/sizeof(arr[0]);
if (findPartiion(arr, n) == true)
printf("Can be divided into two subsets of equal sum");
else
printf("Can not be divided into two subsets of equal sum");
getchar();
return 0;
}
Output:
Can be divided into two subsets of equal sum
Following diagram shows the values in partition table. The diagram is taken form the wiki page of partition problem.

Time Complexity: O(sum*n)
Auxiliary Space: O(sum*n)
Please note that this solution will not be feasible for arrays with big sum.
References:
http://en.wikipedia.org/wiki/Partition_problem
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Intelligent
Solution will work only for +ve numbers. So either we should change the problem statement or change the solution.
public class PartitionProblem { /** * @param args */ public static void main(String[] args) { int A[] = {5, 5, 4, 3, 3}; System.out.println(isSubSet(A, A.length)); } private static boolean isSubSet(int[] A, int length) { int i,partialSum,sum = 0; for(i=0;i<length;i++){ sum +=A[i]; } if(sum%2 == 1)return false; partialSum = sum/2; qSort(A,length); for(i = 0; i < length; i++){ partialSum -= A[i]; if(partialSum < 0) return false; else if(partialSum == 0) return true; } return false; } }nice solution.... thanks
@ anand,
I think your solution will fail for i/p : 3,4,8,9.
Please check and sorry if my observation is incorrect.
Thanks.
@KT:
I modified anand's code and now it's working for all cases.
bool subPartition(int *A, int len){ int sum=0,partitionSum; for(int i=0; i<len;i++){ sum=sum+A[i]; } if(sum%2==1) return false; else{ partitionSum=sum/2; qsort(A,len); //sort in decreasing order for(int i=0; i<len;i++){ while(partitionSum<A[i] && i<len){ i++; } partitionSum=partitionSum-A[i]; if(partitionSum<0) return false; else if(partitionSum==0) return true; } if(partitionSum!=0) return false; } }Patrick, what you are suggesting is a greedy approach. It won't work for the following test case {2,3,4,5,7,9}.
Hi,
I would like to know In what cases sum is less than an array element(it might happen if the array contains -ve numbers).
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
Regarding this code,I think we should return false as question says we need to divide it into two subsets.If we are ignoring any element,the we will create more than 2 subsets.
Please correct me if I am wrong!!!
// If last element is greater than sum, then ignore it
if (arr[n-1] > sum)
return isSubsetSum (arr, n-1, sum);
Regarding this code,I think we should return false as question says we need to divide it into two subsets.If we are ignoring any element,the we will create more than 2 subsets.
Please correct me if I am wrong!!!
*can be done by recursion with O(n^2).
int32_t check_sum ( int32_t array[] , int32_t i , int32_t sum ) {
if (i<max) {
check_sum ( array , i+1 , sum );
sum=sum-array[i];
if ( sum ==0 ) return ans=1;
check_sum ( array , i+1 , sum );
}
}
im wondering if the condition should be:
if (i >= arr[j-1]) part[i][j] = part[i][j-1] || part[i - arr[j-1]][j-1];"Please note that this solution will not be feasible for arrays with big sum."
--->What can be the approach for finding solution with large sum?
#include
#include
#include
int compare(const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main()
{
int a[7];
int sum_even ,sum,m,n,i,flag;
sum_even=sum=m=flag=0;
n=6;
for( i=0;i<7;i++)
{
scanf("%d",&a[i]);
}
qsort(a,7,sizeof(int),compare);
for( i=0;i<7;i++)
{
printf("%d",a[i]);
}
for(i=0;i<7;i++)
{
sum_even+=a[i];
}
if(sum_even%2==0)
{
sum=(sum_even/2);
while(m<=n)
{
if((a[m]+a[n])==sum)
{
flag=1;
break;
}
if((a[m]+a[n])<sum)
m++;
else
n--;
}
if(flag==1)
printf("possible");
}
else
printf("not possible");
getch();
return 0;
}
Plz clearify ur method.
i think there is a error in explanation of part[i][j], it should be
part[i][j] = true if a subset of {arr[0], arr[1], ..arr[j-1]} has sum equal to **** i *****, otherwise false '
***** are used to highlight.
@Abhinav Priyadarshi: Thanks for pointing this out. We have corrected the explanation. Keep it up!
Hi, I am using a top-down recursive memoization to populate the cache array below.
I want to know :
1. Whether following solution is correctly implemented.
2. I don't see the sub-problems being reused in the cache array so a bottom up approach may be having most of the entries unused (and populated nonethless).
int arr[] = {3, 1, 1, 2, 2, 1}; int N, S; int cache[MAXN][MAXSUM]; bool partition(int pos, int sum) { if (sum == S>>1) { return true; } if (pos == N || sum > S>>1) { return false; } if (cache[pos][sum] != -1) { return cache[pos][sum]; } cache[pos][sum] = partition(pos+1, sum+arr[pos]) || partition(pos+1, sum); return cache[pos][sum]; }I have initialized cache to -1 and S to total Sum.
space optimized DP approach :-
part[0]=1; for(i=0;i<n;i++) { for(j=sum;j>=arr[i];j--) { part[j]=part[j] | part[j-arr[i]] } } if(part[sum]) printf("\nsubset exists\n");here sum=Total_Sum/2;
Condn- sum should be divisible by 2;
We know the "sum" right !!! sum = sum of all the elements in array
Cant we use sum of subset problem (knapsack) to find out the subset which has "sum/2" value. it would become so easy because we know that the rest of elements sum is "sum/2",
I think that is what the given DP code is doing
Oops .. My Bad ...
But why are they using 2D array .... I guess 1D array of SUM/2 is enough. ???
Sort the data in descending order for(i=1 to n) { if(sum(set1) > sum(set2)) include the number in set2 else if(sum(set2) > sum(set1)) include the number in set1 else return 1; } retunr 0;this will not work for {5, 5, 4, 3, 3}
How is different from fair work load problem?
http://topcoder.bgcoder.com/print.php?id=383
Reference: The Algorithm Design Manual by Skiena.
Hi, thanks for sharing the problem.
I can think of a recursive backtracking solution (do not know if it's right) :
If workers == 0 return 0 else calculate all possible partition(folders, N, sum/N) say newfolders // sum is total count of the elements in folders and N is #workers. foreach newfolders max = maximum of (sum(folders)-sum(newfolders), getMostWork(newfolders, workers-1)) and max return maxCan you hint at a solution ?