Example 1
- Input
- nums = [5,-7,3,5], goal = 6
- Output
- 0
Taking all four values yields 6. Its left sum -2 and right sum 8 give zero distance.
Find the smallest absolute difference between a subsequence sum and a target. Split up to forty values, enumerate half sums and search sorted complements.
Given nums and goal, choose any subsequence, including the empty subsequence, and return the minimum abs(sum-goal). The official exercise allows negative numbers, so a sum that currently exceeds goal cannot safely be pruned. Only the distance is required; different subsequences with the same sum are equivalent answers.
1 <= nums.length <= 40.-10^7 <= nums[i] <= 10^7.-10^9 <= goal <= 10^9.Taking all four values yields 6. Its left sum -2 and right sum 8 give zero distance.
The subset [7,-9,-2] sums to -4, distance one. Enumerating all half pairs shows that no sum equals -5.
Every nonempty sum is positive. The empty subset sums to zero and is the closest.
All four subsets sum to zero. Duplicate sums do not change the minimum distance.
Forty elements have over a trillion subsets, but twenty have about a million. Divide the array into two halves. Every full subset consists of one subset from each half, so enumerate each half separately and look for pairs whose sums approach goal. In Example 1 the halves [5,-7] and [3,5] produce sums [0,5,-7,-2] and [0,3,5,8]. Left sum -2 pairs with right sum 8 to reach goal 6 exactly. Including zero in both lists represents the empty subset and subsets confined to one half.
Reveal Meet in the Middle: intuition, complexity, and code
Meet in the Middle trades two manageable exponential lists for one infeasible full search. Enumeration preserves all possibilities, while sorted nearest-neighbor search avoids testing their Cartesian product.