[LeetCode] Minimize the Difference Between Target and Chosen Elements

1981. Minimize the Difference Between Target and Chosen Elements

You are given an m x n integer matrix mat and an integer target.

Choose one integer from each row in the matrix such that the absolute difference between target and the sum of the chosen elements is minimized.

Return the minimum absolute difference.

The absolute difference between two numbers a and b is the absolute value of a - b.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int minimizeTheDifference(vector<vector<int>>& mat, int target) {
set<int> cs{0}, ns;
int res;
for(int i = 0; i < mat.size(); i++) {
sort(mat[i].begin(), mat[i].end());
res = INT_MAX;
for(auto& prev: cs) {
for(auto& row: mat[i]) {
if(prev + row <= target || ns.empty() || res > abs(prev + row - target)) {
res = min(res, abs(prev + row - target));
ns.insert(prev + row);
}
}
}
cs = ns;
ns.clear();
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/22/PS/LeetCode/minimize-the-difference-between-target-and-chosen-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.