![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
0
Time Complexity: O(2^n/2)
Auxiliary Space: O(2^n/2)