Closest Subsequence Sum
Learn this problemProblem statement
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.
Function
minAbsDifference(nums: int[], goal: int) → intExamples
Example 1
nums = [5, -7, 3, 5]goal = 6return = 0Choose the whole array as a subsequence, with a sum of 6. This is equal to the goal, so the absolute difference is 0.
Example 2
nums = [7, -9, 15, -2]goal = -5return = 1Choose the subsequence [7, -9, -2], with a sum of -4. The absolute difference is abs(-4 - (-5)) = abs(1) = 1, which is the minimum.
Example 3
nums = [1, 2, 3]goal = -7return = 7No subsequence can get closer than an absolute difference of 7 from the goal.
Constraints
1 <= nums.length <= 40-10^7 <= nums[i] <= 10^7-10^9 <= goal <= 10^9
More Salesforce problems
- Minimize Total Input Cost (for LTMS)Seen Jun 2026
- Count Prime StringsONSITE INTERVIEW · Seen Jun 2026
- Final Pod Counts After LogsOA · Seen May 2026
- ATM Queue Exit OrderPHONE SCREEN · Seen May 2026
- Good Ways to Split an ArrayPHONE SCREEN · Seen May 2026
- Generate Seen Binary StringsOA · Seen May 2026
- Update Pod Counts From LogsOA · Seen May 2026
- Minimum Removals to Balance ArrayOA · Seen May 2026