-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path1818.minimum-absolute-sum-difference.py
46 lines (38 loc) · 1.2 KB
/
1818.minimum-absolute-sum-difference.py
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
35
36
37
38
39
40
41
42
43
44
45
46
#
# @lc app=leetcode id=1818 lang=python3
#
# [1818] Minimum Absolute Sum Difference
#
# @lc code=start
# TAGS: Binary Search, Greedy
class Solution:
"""
Approach:
Sort nums1 and perform binary search on it to find best gain
"""
# 91.99%. Time: O(NlogN). Space: O(sort)
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
# bisect right
def binary_search(nums, target):
lo, hi = 0, len(nums)
while lo < hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
lo = mid + 1
else:
hi = mid
return lo
nums = sorted(nums1)
total = gain = 0
for n1, n2 in zip(nums1, nums2):
total += abs(n1 - n2)
index = binary_search(nums, n2)
# Get most change
if index:
gain = max(gain, abs(n1 - n2) - abs(nums[index - 1] - n2))
if index < len(nums):
gain = max(gain, abs(n1 - n2) - abs(nums[index] - n2))
return (total - gain) % (10**9 + 7)
# @lc code=end