[LeetCode] Closest Subsequence Sum

1755. Closest Subsequence Sum

You are given an integer array nums and an integer goal.

You want to choose a subsequence of nums such that the sum of its elements is the closest possible to goal. That is, if the sum of the subsequence’s elements is sum, then you want to minimize the absolute difference abs(sum - goal).

Return the minimum possible value of abs(sum - goal).

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
public:
int minAbsDifference(vector<int>& nums, int goal) {
int res = abs(goal), sz = nums.size();



set<int> left{0}, right{0};
for(int i = 0; i < sz / 2; i++) {
for(auto n : vector<int>(left.begin(), left.end())) {
if(left.insert(n + nums[i]).second);
res = min(res, abs(goal - n - nums[i]));
}
}

for(int i = sz / 2; i < sz; i++) {
for(auto n : vector<int>(right.begin(), right.end())) {
if(right.insert(n + nums[i]).second) {
res = min(res, abs(goal - n - nums[i]));
auto it = left.lower_bound(goal - n - nums[i]);
if(it != end(left)) {
res = min(res, abs(goal - n - nums[i] - *(it)));
}
if(it != begin(left)) {
res = min(res, abs(goal - n - nums[i] - *prev(it)));
}
if(!res) return res;
}
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/25/PS/LeetCode/closest-subsequence-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.