LeetCode solutions

1881. Closest Subsequence Sum

My accepted Python solution to LeetCode problem 1881, Closest Subsequence Sum, running in 804ms.

  • Difficulty: Hard
  • Python
  • Runtime 804ms
  • Memory 187.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 804ms, memory 187.6MB, accepted 2025-12-29.

python
class Solution:
    def minAbsDifference(self, nums: List[int], goal: int) -> int:
        from bisect import bisect_left
        n = len(nums)
        mid = n // 2
        def get_sums(arr):
            sums = {0}
            for x in arr:
                sums = sums | {s + x for s in sums}
            return sums
        left = sorted(get_sums(nums[:mid]))
        right = sorted(get_sums(nums[mid:]))
        ans = abs(goal)
        for s1 in left:
            t = goal - s1
            i = bisect_left(right, t)
            if i < len(right):
                ans = min(ans, abs(s1 + right[i] - goal))
            if i > 0:
                ans = min(ans, abs(s1 + right[i-1] - goal))
        return ans

Source