Skip to content

Commit 81cf886

Browse files
authored
Create minimum-absolute-sum-difference.cpp
1 parent e8ba315 commit 81cf886

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
7+
static const int MOD = 1e9 + 7;
8+
9+
vector<int> sorted_nums1(cbegin(nums1), cend(nums1));
10+
sort(begin(sorted_nums1), end(sorted_nums1));
11+
int result = 0, max_change = 0;
12+
for (int i = 0; i < size(nums2); ++i) {
13+
int diff = abs(nums1[i] - nums2[i]);
14+
result = (result + diff) % MOD;
15+
if (diff < max_change) {
16+
continue;
17+
}
18+
const auto cit = lower_bound(cbegin(sorted_nums1), cend(sorted_nums1), nums2[i]);
19+
if (cit != cend(sorted_nums1)) {
20+
max_change = max(max_change, diff - abs(*cit - nums2[i]));
21+
}
22+
if (cit != cbegin(sorted_nums1)) {
23+
max_change = max(max_change, diff - abs(*prev(cit) - nums2[i]));
24+
}
25+
}
26+
return (result - max_change + MOD) % MOD;
27+
}
28+
};

0 commit comments

Comments
 (0)