Minimum Incompatibility - Problem

You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.

A subset's incompatibility is the difference between the maximum and minimum elements in that array.

Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.

A subset is a group of integers that appear in the array with no particular order.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1,4], k = 2
Output: 4
💡 Note: Optimal distribution: [1,4] and [1,2]. Incompatibilities: (4-1) + (2-1) = 3 + 1 = 4
Example 2 — Impossible Case
$ Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
💡 Note: Each subset has size 2. Possible distribution: [1,2], [1,3], [3,6], [2,8] with incompatibilities 1+2+3+6=12, but optimal is different
Example 3 — All Same Elements
$ Input: nums = [5,5,5,5], k = 2
Output: -1
💡 Note: Cannot form 2 subsets without duplicate elements since all elements are the same

Constraints

  • 1 ≤ k ≤ nums.length ≤ 16
  • nums.length is divisible by k
  • 1 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Minimum Incompatibility - DP Approach INPUT nums array: 1 idx 0 2 idx 1 1 idx 2 4 idx 3 Parameters: k = 2 (subsets) subset size = 4/2 = 2 Constraint: No duplicates in same subset Goal: Minimize sum of (max - min) for each subset ALGORITHM STEPS 1 Sort Array [1,1,2,4] - helps find min/max efficiently 2 DP with Bitmask State: which elements are used (2^n states) 3 Try All Subsets For each valid subset of size n/k 4 Minimize Total Sum incompatibilities across all k subsets Possible Distributions: Option A: {1,2} + {1,4} incompat: 1 + 3 = 4 Option B: {1,4} + {1,2} incompat: 3 + 1 = 4 FINAL RESULT Optimal Distribution: Subset 1: {1, 2} max - min = 2 - 1 = 1 Subset 2: {1, 4} max - min = 4 - 1 = 3 + Total Sum: 1 + 3 = 4 Output: 4 Key Insight: DP with bitmask explores all valid subset combinations. Each state represents which elements have been assigned. For each subset, we ensure no duplicates and calculate (max - min). Time: O(n * 3^n). Sorting first ensures we can quickly identify min/max of any subset by its first and last elements. TutorialsPoint - Minimum Incompatibility | DP with Bitmask Approach
Asked in
Google 15 Facebook 8
12.0K Views
Medium Frequency
~45 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen