|
| 1 | +/** |
| 2 | + * 1755. Closest Subsequence Sum |
| 3 | + * https://leetcode.com/problems/closest-subsequence-sum/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an integer array nums and an integer goal. |
| 7 | + * |
| 8 | + * You want to choose a subsequence of nums such that the sum of its elements is the closest |
| 9 | + * possible to goal. That is, if the sum of the subsequence's elements is sum, then you want |
| 10 | + * to minimize the absolute difference abs(sum - goal). |
| 11 | + * |
| 12 | + * Return the minimum possible value of abs(sum - goal). |
| 13 | + * |
| 14 | + * Note that a subsequence of an array is an array formed by removing some elements (possibly |
| 15 | + * all or none) of the original array. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + * @param {number} goal |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var minAbsDifference = function(nums, goal) { |
| 24 | + const n = nums.length; |
| 25 | + const half = Math.floor(n / 2); |
| 26 | + const leftSums = new Set(); |
| 27 | + const rightSums = new Set(); |
| 28 | + |
| 29 | + generateSums(0, half, leftSums); |
| 30 | + generateSums(half, n, rightSums); |
| 31 | + |
| 32 | + const rightArray = [...rightSums].sort((a, b) => a - b); |
| 33 | + let minDiff = Infinity; |
| 34 | + |
| 35 | + for (const leftSum of leftSums) { |
| 36 | + const target = goal - leftSum; |
| 37 | + let left = 0; |
| 38 | + let right = rightArray.length - 1; |
| 39 | + |
| 40 | + while (left <= right) { |
| 41 | + const mid = Math.floor((left + right) / 2); |
| 42 | + const sum = leftSum + rightArray[mid]; |
| 43 | + minDiff = Math.min(minDiff, Math.abs(sum - goal)); |
| 44 | + |
| 45 | + if (sum < goal) { |
| 46 | + left = mid + 1; |
| 47 | + } else { |
| 48 | + right = mid - 1; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + return minDiff; |
| 54 | + |
| 55 | + function generateSums(start, end, sums, current = 0) { |
| 56 | + if (start === end) { |
| 57 | + sums.add(current); |
| 58 | + return; |
| 59 | + } |
| 60 | + generateSums(start + 1, end, sums, current); |
| 61 | + generateSums(start + 1, end, sums, current + nums[start]); |
| 62 | + } |
| 63 | +}; |
0 commit comments