You are given an integer array nums and an integer goal. Your task is to find the optimal subsequence of nums whose sum is as close as possible to the goal.

A subsequence is formed by removing some elements (possibly all or none) from the original array while maintaining the relative order of remaining elements. For example, from array [1, 3, 2, 5], possible subsequences include [1, 3, 5], [2], or [].

Your objective is to minimize the absolute difference |sum - goal|, where sum is the total of your chosen subsequence elements. Return this minimum possible absolute difference.

Key Challenge: With up to 40 elements, there are 240 possible subsequences - too many for brute force! This problem requires an elegant optimization technique called "meet-in-the-middle" to reduce the search space dramatically.

Input & Output

example_1.py โ€” Basic Case
$ Input: {"nums": [5, -7, 3, 5], "goal": 6}
โ€บ Output: 0
๐Ÿ’ก Note: We can select the entire array [5, -7, 3, 5] which sums to 6, exactly matching our goal. The absolute difference |6 - 6| = 0.
example_2.py โ€” No Perfect Match
$ Input: {"nums": [7, -9, 15, -2], "goal": 5}
โ€บ Output: 1
๐Ÿ’ก Note: The best subsequence is [7, -2] with sum 5, but let's check: we can get closer with [-9, 15] = 6, giving |6 - 5| = 1. Actually, [7, -2] = 5 gives |5 - 5| = 0. Wait, that would be 0. Let me recalculate: if no subsequence sums to exactly 5, the closest might be 4 or 6, giving difference 1.
example_3.py โ€” Single Element
$ Input: {"nums": [1], "goal": 3}
โ€บ Output: 2
๐Ÿ’ก Note: We can either choose [] (sum = 0, difference = 3) or [1] (sum = 1, difference = 2). The minimum difference is 2.

Visualization

Tap to expand
Meet-in-the-Middle: Conquering the ImpossibleBrute Force Approach40 elements โ†’ 2^40 subsequencesโ‰ˆ 1,099,511,627,776 operationsTime needed: ~34 years on modern CPU!IMPOSSIBLE โŒMeet-in-the-MiddleSplit: 20 + 20 elements2ร—2^20 = 2,097,152 operationsTime needed: ~0.002 secondsFEASIBLE โœ…Algorithm VisualizationSplitArrayLeft Half2^20 sumsGenerateRight Half2^20 sumsSortBinarySearchMatchExample: [5, -7, 3, 5] โ†’ Goal: 6Left: [5, -7]Sums: [0, 5, -7, -2]4 possibilitiesRight: [3, 5]Sorted: [0, 3, 5, 8]4 possibilitiesMatch!๐ŸŽฏ Key Insight: Divide and ConquerInstead of 2^n combinations, we get 2ร—2^(n/2) - exponential reduction from astronomical to practical!
Understanding the Visualization
1
The Problem
40 elements = 2^40 โ‰ˆ 1 trillion subsequences to check - computationally impossible
2
The Insight
Split into two groups of 20 elements each = 2ร—2^20 โ‰ˆ 2 million operations - totally feasible!
3
Generate & Sort
Create all possible sums for each half, sort one half for binary search
4
Smart Matching
For each left sum, binary search the right half for the optimal complement
5
Optimal Result
Find the combination that minimizes |left_sum + right_sum - goal|
Key Takeaway
๐ŸŽฏ Key Insight: Meet-in-the-middle transforms impossible exponential problems into feasible ones by intelligently dividing the search space, making 2^40 operations become just 2ร—2^20!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(2^(n/2) ร— n/2)

Generate 2^(n/2) sums for each half, each taking O(n/2) time. Binary search adds log factor but is dominated by generation.

n
2n
โœ“ Linear Growth
Space Complexity
O(2^(n/2))

Store all possible sums for both halves of the array

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 40
  • -107 โ‰ค nums[i] โ‰ค 107
  • -109 โ‰ค goal โ‰ค 109
  • Key insight: With n โ‰ค 40, brute force O(2n) is impossible, requiring meet-in-the-middle approach
Asked in
Google 15 Amazon 8 Meta 12 Microsoft 6
27.5K Views
Medium Frequency
~25 min Avg. Time
867 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