-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrPartition_MinDiff.java
47 lines (45 loc) · 1.72 KB
/
ArrPartition_MinDiff.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Arrays;
public class Solution {
public int minimumDifference(int[] nums) {
int n = nums.length;
if (n == 2) return Math.abs(nums[1] - nums[0]);
int[][] lists1 = generate(Arrays.copyOfRange(nums, 0, n / 2));
int[][] lists2 = generate(Arrays.copyOfRange(nums, n / 2, n));
int ans = Integer.MAX_VALUE;
for (int d = 0; d <= n / 2; d++) {
int[] arr1 = lists1[d], arr2 = lists2[d];
int k = arr1.length;
int i1 = 0, i2 = 0; // we use two pointers to find two elements in arr1, arr2 with minimum absolute difference
while (i1 < k && i2 < k) {
int diff = arr1[i1] - arr2[i2];
ans = Math.min(ans, Math.abs(diff));
if (diff <= 0) i1++;
if (diff >= 0) i2++;
}
}
return ans;
}
private static int[][] generate(int[] nums) {
int n = nums.length;
int total = 0;
for (int num : nums) total += num;
int[][] ans = new int[n + 1][];
int[] pos = new int[n + 1];
for (int i = 0, binomial = 1; i <= n; i++) {
ans[i] = new int[binomial]; // number of ways to choose i from n = binomial(i,n)
binomial = binomial * (n - i) / (i + 1);
}
int maxValue = 1 << n;
for (int key = 0; key < maxValue; key++) {
int sum1 = 0;
for (int i = 0; i < n; i++) {
if ((key >> i & 1) == 1) sum1 += nums[i];
}
int sum2 = total - sum1;
int bits = Integer.bitCount(key);
ans[bits][pos[bits]++] = sum1 - sum2;
}
for (int[] arr : ans) Arrays.sort(arr);
return ans;
}
}