#1755

Closest Subsequence Sum

master · 1615 · lc hard +32 · verified · 43.2% accepted · 1,004 likes · top 25%

Description

You are given an integer array nums and an integer goal. Choose a subsequence of nums to minimize abs(sum - goal). Return the minimum possible value of abs(sum - goal).

Example 1:

Input: nums = [5,-7,3,5], goal = 6
Output: 0
Explanation: Choose 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:

Input: nums = [7,-9,15,-2], goal = -5
Output: 1
Explanation: Choose 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:

Input: nums = [1,2,3], goal = -7
Output: 7

Code

1
2
3