Problem Description
Given an integer array and an integer k, you are required to partition the array into k subsets of equal size such that no subset contains duplicate elements. The incompatibility of a subset is defined as the difference between its maximum and minimum elements. The goal is to minimize the total sum of incompatibilities among all k subsets. If it is not possible to form such k subsets, return -1.
Key Insights
- The total number of elements is n and must be divisible by k (subset size = n / k).
- For each subset, if there are duplicate values the subset is invalid.
- Precompute all possible valid subsets (using bit masks) that have exactly subset size elements and store their incompatibility (max - min).
- Use dynamic programming with bitmasking where each bit represents whether an element from the original array has been used.
- For each state (mask) in DP, try to add one of the valid groups (bit masks) that do not conflict with the current state.
- The answer will be the minimum sum computed when all elements are used; otherwise return -1.
Space and Time Complexity
Time Complexity: O(2^n * V) where V is the number of valid groups (which is bounded by C(n, n/k)), making it feasible for n up to 16. Space Complexity: O(2^n) for the DP table and precomputed valid groups.
Solution
The solution involves two main phases:
- Precomputation: Iterate over all bit masks of size n. For subsets of size equal to n/k, check for duplicates. If a subset is valid, compute its incompatibility (max - min) and store it.
- Dynamic Programming: Use a DP array of size 2^n, where each index represents a subset of chosen indices. Start from the empty subset (mask = 0) and try to add valid group masks which do not intersect with the current state. Update the DP state to reflect the minimal incompatibility sum to reach that state. The answer is found when the DP state for mask = (1<<n) - 1 is reached.