4
public int minAbsDifference(int[] nums, int goal) {8
List<Integer> first = new ArrayList<>();9
List<Integer> second = new ArrayList<>();11
generate(0, n / 2, 0, first); // generate all possible subset sums from half the array13
n / 2, n, 0, second); // generate all possible subset sums from the second half of the array15
Collections.sort(first);16
int ans = Integer.MAX_VALUE;18
for (int secondSetSum : second) {19
int left = goal - secondSetSum; // How far off are we from the desired goal?22
> left) { // all subset sums from first half are too big => Choose the smallest23
ans = (int) (Math.min(ans, Math.abs((first.get(0) + secondSetSum) - goal)));26
if (first.get(first.size() - 1)27
< left) { // all subset sums from first half are too small => Choose the largest28
ans = (int) (Math.min(ans, Math.abs((first.get(first.size() - 1) + secondSetSum) - goal)));31
int pos = Collections.binarySearch(first, left);32
if (pos >= 0) // Exact match found! => first.get(pos) + secondSetSum == goal34
else // If exact match not found, binarySearch in java returns (-(insertionPosition) - 1)44
- goal)); // Checking for the floor value (largest sum < goal)52
- goal)); // Checking for the ceiling value (smallest sum > goal)57
/** Generating all possible subset sums. 2 choices at each index,i -> pick vs do not pick */58
void generate(int i, int end, int sum, List<Integer> listOfSubsetSums) {60
listOfSubsetSums.add(sum); // add63
generate(i + 1, end, sum + arr[i], set);64
generate(i + 1, end, sum, set);