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: 7
💡 Note: We can choose empty subsequence (sum=0) with difference |0-(-7)| = 7, or choose [1] with difference |1-(-7)| = 8. The minimum is 7.

Constraints

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

Visualization

Tap to expand
Closest Subsequence Sum - Meet in the Middle INPUT nums array: 5 [0] -7 [1] 3 [2] 5 [3] Goal 6 Split into two halves: Left Half [5, -7] Right Half [3, 5] Find subsequence sum closest to goal = 6 Minimize |sum - goal| ALGORITHM STEPS 1 Generate Left Sums All subseq of [5,-7]: {0, 5, -7, -2} 2 Generate Right Sums All subseq of [3,5]: {0, 3, 5, 8} 3 Sort Right Sums For binary search: [0, 3, 5, 8] 4 Binary Search For each left sum L: Find R in right closest to (goal - L) = (6 - L) L=-2: need R=8, found 8 Sum = -2 + 8 = 6 |6 - 6| = 0 (OK!) FINAL RESULT Optimal Subsequence Found: -7 + 5 + 3 From original array indices: [1,2,3] Sum = -7 + 5 + 3 = 6 Absolute Difference: |6 - 6| = |0| = 0 OUTPUT 0 (Minimum possible - OK) Key Insight: Meet in the Middle splits the problem: instead of checking 2^n subsequences (2^4=16), we check 2^(n/2) + 2^(n/2) = 2^2 + 2^2 = 8 sums. For each left sum L, binary search finds the right sum R closest to (goal - L). Time: O(2^(n/2) * log(2^(n/2))) = O(n * 2^(n/2)) vs O(2^n) brute force. TutorialsPoint - Closest Subsequence Sum | Meet in the Middle Approach
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