Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Java/Program-21/K_Equal_Sum_Subset.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
public class K_Equal_Sum_Subset {
//helper function
boolean helpInPartition(int nums[],boolean visited[],int start,int k,int currentSum,int targetSum)
{
//when there are no more subsets left to make
if(k==0)
return true;
if(currentSum>targetSum)
return false;
//if current sum equals target sum,we are left with k-1 subsets to make
if(currentSum==targetSum)
return helpInPartition(nums,visited,0,k-1,0,targetSum);
for(int j=start;j<nums.length;j++)
{
//if nums[j] is already included in a subset skip this iteration
if(visited[j])
continue;
//let us assume nums[j] is a part of the current subset
visited[j]=true;
//current sum < target sum,we look for elements beyond j
if(helpInPartition(nums,visited,j+1,k,currentSum+nums[j],targetSum))
return true;
//if nums[j] is not a part of the current subset , we mark it unvisited
visited[j]=false;
}
return false;
}
public boolean canPartitionKSubsets(int[] nums, int k) {
int sum=0;
for(int i:nums)
sum+=i;
//nums can be divided into k equal sum subsets only if the sum of its elements is divisible by k
if(sum%k!=0)
return false;
//visited array to keep track where an element is already a part of a subset or not
boolean visited[]=new boolean[nums.length];
return helpInPartition(nums,visited,0,k,0,sum/k);
}
}
11 changes: 11 additions & 0 deletions Java/Program-21/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Program 21

Program to Partition to K Equal Sum Subsets

Given an integer array nums and an integer k, return true if it is possible to divide this array into k non-empty subsets whose sums are all equal.

Example 1:

Input: nums = [4,3,2,3,5,2,1], k = 4
Output: true
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.