Closest Subsequence Sum

You are given an integer array nums and an integer goal.

You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence's elements is sum, then you want to minimize the absolute difference abs(sum - goal).

Return the minimum possible value of abs(sum - goal).

Note that a subsequence of an array is an array formed by removing some elements (possibly all or none) of the original array.

 

Example 1:

Input: nums = [5,-7,3,5], goal = 6
Output: 0
Explanation: Choose the whole array as a subsequence, with a sum of 6.
This is equal to the goal, so the absolute difference is 0.

Example 2:

Input: nums = [7,-9,15,-2], goal = -5
Output: 1
Explanation: Choose the subsequence [7,-9,-2], with a sum of -4.
The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.

Example 3:

Input: nums = [1,2,3], goal = -7
Output: 7

 

Constraints:


Solution:

divide arr into two arrays, and generate subset sums for each array, and then do a 2 sum on the goal

class Solution {
    public int minAbsDifference(int[] nums, int goal) {
        Set<Integer> set1 = new HashSet();
        TreeSet<Integer> set2 = new TreeSet();
        generate(nums, 0, nums.length / 2, 0,  set1);
        generate(nums, nums.length / 2, nums.length, 0, set2);
        int result = Integer.MAX_VALUE;
        for (int left : set1) {
            int target = goal - left;
            if (set2.contains(target)) {
                return 0;
            }
            Integer small = set2.lower(target);
            if (small != null) result = Math.min(result, Math.abs(left + small - goal));
            Integer big = set2.higher(target);
            if (big != null) result = Math.min(result, Math.abs(left + big - goal));
        }
        return result;    
    }
    
    private void generate(int[] nums, int i, int end, int sum, Set<Integer> set) {
        if (i == end) {
            set.add(sum);
            return;
        }
        generate(nums, i + 1, end, sum, set);
        generate(nums, i + 1, end, sum + nums[i], set);
    }
}