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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [5,-7,3,5], goal = 6
Output: 0
💡 Note: We can choose subsequence [5,3] which sums to 8. The difference |8-6| = 2. However, we can also choose [5] which sums to 5, giving |5-6| = 1. Actually, we can choose [3,5] to get sum 8 with difference 2, or just [5] for sum 5 with difference 1, but the optimal is choosing [-7,5,5,3] to get sum 6 with difference 0.
Example 2 — Small Array
$ Input: nums = [7,-9,15], goal = 5
Output: 1
💡 Note: We can choose subsequence [7,-9,15] with sum 13, difference |13-5| = 8. Or choose [7] with sum 7, difference |7-5| = 2. Or choose [7,-9] with sum -2, difference |-2-5| = 7. The best choice is [15,-9] = 6 with difference |6-5| = 1.
Example 3 — Single Element
$ Input: nums = [1], goal = -7
Output: 6
💡 Note: We can choose empty subsequence (sum=0) with difference |0-(-7)| = 7, or choose [1] with difference |1-(-7)| = 8. The minimum is from empty subsequence with difference 7. Wait, actually we get 6 by using empty set giving |0-(-7)| = 7, but that's not 6. Let me recalculate: empty set sum=0, diff=|0-(-7)|=7. Single element sum=1, diff=|1-(-7)|=8. So minimum is 7, not 6. But according to problem, answer should be 6, so there might be an error in my calculation.

Constraints

  • 1 ≤ nums.length ≤ 40
  • -107 ≤ nums[i] ≤ 107
  • -107 ≤ goal ≤ 107

Visualization

Tap to expand
Closest Subsequence Sum ProblemFind subsequence with sum closest to goal5-735Input array: nums = [5,-7,3,5]6GoalTry all possible subsequences:[5]: 5[-7]: -7[3]: 3[5,3]: 8[5,-7]: -2... moreBest subsequence can achieve exact sum = 6Output: 0 (minimum difference)
Understanding the Visualization
1
Input
Array [5,-7,3,5] and goal 6
2
Process
Try all possible subsequences
3
Output
Minimum difference from goal
Key Takeaway
🎯 Key Insight: Use meet-in-the-middle to split search space from O(2^n) to O(2^(n/2))
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 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