Closest Subsequence Sum - Problem
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code