VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-closest-subsequence-sum-to-target/

⇱ Find the Closest Subsequence Sum to Target - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the Closest Subsequence Sum to Target

Last Updated : 23 Jul, 2025

Given an integer array arr[] and an integer target. The task is to find a subsequence of arr such that the absolute difference between the sum of its elements and target is minimized. Return the minimum possible value of abs(sum - target).

Note: Subsequence of an array is an array formed by removing some (possibly all or none) of the original elements.

Examples:

Input: arr = [5, -7, 3, 5], target = 6
Output: 0
Explanation: Choose the whole array as a subsequence, with a sum of 6. This is equal to the target, so the absolute difference is 0.

Input: arr = [1, 2, 3], target = -7
Output: 7
Explanation: Choosing no elements results in a sum of 0, which is the closest to -7.

Approach:

To solve this problem, we need to find a way to explore all possible subsequences efficiently. One effective approach is to use the "meet in the middle" technique. We split the array into two halves and consider all possible sums for each half. By doing so, we reduce the problem size and can find the closest sum to the target efficiently using binary search.

Steps-by-step approach:

  • Split the array arr into two halves.
  • Calculate all possible sums of subsequences for each half.
  • Sort the list of sums from the second half.
  • For each sum in the first half, use binary search on the sorted sums of the second half to find the closest possible sum to the target.
  • Keep track of the minimum absolute difference between the total sum and the target.
  • Return the minimum absolute difference found.

Below is the implementation of the above approach:


Output
0

Time Complexity: O(2^n/2)
Auxiliary Space: O(2^n/2)

Comment