#1755
Closest Subsequence Sum
HardArrayTwo PointersDynamic ProgrammingBit ManipulationSortingBitmaskMeet-in-the-MiddleBinary SearchBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(2^n) | O(n * 2^(n/2)) |
| Space | O(1) | O(2^(n/2)) |
💡
Intuition
Time O(n * 2^(n/2))Space O(2^(n/2))
The optimal solution leverages the idea of dividing the array into two halves and using a meet-in-the-middle approach. This reduces the problem size significantly and allows us to efficiently find the closest sum to the goal.
⚙️
Algorithm
4 steps- 1Step 1: Split the array into two halves.
- 2Step 2: Generate all possible sums for both halves.
- 3Step 3: Sort one of the halves' sums to enable binary search.
- 4Step 4: For each sum from the first half, use binary search to find the closest sum in the second half that, when added, is closest to the goal.
solution.py34 lines
1# Full working Python code
2from itertools import combinations
3
4
5def closest_subsequence_sum(nums, goal):
6 n = len(nums)
7 left_part = nums[:n//2]
8 right_part = nums[n//2:]
9 left_sums = set()
10 right_sums = set()
11
12 for i in range(len(left_part) + 1):
13 for comb in combinations(left_part, i):
14 left_sums.add(sum(comb))
15
16 for i in range(len(right_part) + 1):
17 for comb in combinations(right_part, i):
18 right_sums.add(sum(comb))
19
20 left_sums = sorted(left_sums)
21 min_diff = float('inf')
22
23 for s in right_sums:
24 target = goal - s
25 l, r = 0, len(left_sums) - 1
26 while l <= r:
27 mid = (l + r) // 2
28 min_diff = min(min_diff, abs(left_sums[mid] + s - goal))
29 if left_sums[mid] + s < goal:
30 l = mid + 1
31 else:
32 r = mid - 1
33
34 return min_diffℹ
Complexity note: The time complexity is O(n * 2^(n/2)) because we generate all possible sums for two halves of the array (2^(n/2) each) and sort one of them. The space complexity is O(2^(n/2)) due to storing the sums.
- 1Dividing the problem into smaller parts can significantly reduce complexity.
- 2Using binary search on sorted sums allows for efficient closest sum calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.