<p>You are given an integer array <code>nums</code> and an integer <code>goal</code>.</p>

<p>You want to choose a subsequence of <code>nums</code> such that the sum of its elements is the closest possible to <code>goal</code>. That is, if the sum of the subsequence&#39;s elements is <code>sum</code>, then you want to <strong>minimize the absolute difference</strong> <code>abs(sum - goal)</code>.</p>

<p>Return <em>the <strong>minimum</strong> possible value of</em> <code>abs(sum - goal)</code>.</p>

<p>Note that a subsequence of an array is an array formed by removing some elements <strong>(possibly all or none)</strong> of the original array.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [5,-7,3,5], goal = 6
<strong>Output:</strong> 0
<strong>Explanation:</strong> Choose the whole array as a subsequence, with a sum of 6.
This is equal to the goal, so the absolute difference is 0.
</pre>

<p><strong class="example">Example 2:</strong></p>

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

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3], goal = -7
<strong>Output:</strong> 7
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 40</code></li>
	<li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= goal &lt;= 10<sup>9</sup></code></li>
</ul>

from sortedcontainers import SortedList

class Solution:
    def minAbsDifference(self, nums: List[int], goal: int) -> int:
        n = len(nums)
        mid = n // 2
    
        # 配列を2つに分割
        left = nums[:mid]
        right = nums[mid:]
    
        # 部分和を全て計算する関数
        def compute_subarray_sums(array):
            sums = set()
            n = len(array)
            for i in range(n + 1):
                for comb in combinations(array, i):
                    sums.add(sum(comb))
            return sums
    
        # 左右の部分列の和を計算
        left_sums = compute_subarray_sums(left)
        right_sums = compute_subarray_sums(right)
    
        # 右の部分列の和をソートしておく
        right_sums = sorted(right_sums)
    
        # 最小差の初期化
        min_diff = float('inf')
    
        # 左の部分列の和を固定し、右の部分列の和を2分探索で見つける
        for left_sum in left_sums:
            # 二分探索で最も近い値を見つける
            lo, hi = 0, len(right_sums) - 1
            while lo <= hi:
                mid = (lo + hi) // 2
                current_sum = left_sum + right_sums[mid]
                min_diff = min(min_diff, abs(current_sum - goal))
    
                if current_sum < goal:
                    lo = mid + 1
                else:
                    hi = mid - 1
    
        return min_diff
179500