forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minimize-the-maximum-of-two-arrays.py
64 lines (55 loc) · 1.66 KB
/
minimize-the-maximum-of-two-arrays.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Time: O(log(min(d1, d2)))
# Space: O(1)
# number theory
class Solution(object):
def minimizeSet(self, divisor1, divisor2, uniqueCnt1, uniqueCnt2):
"""
:type divisor1: int
:type divisor2: int
:type uniqueCnt1: int
:type uniqueCnt2: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def lcm(a, b):
return a//gcd(a, b)*b
def count(cnt, d1, d2):
l = lcm(d1, d2)
return cnt+cnt//(l-1)-int(cnt%(l-1) == 0)
return max(count(uniqueCnt1, divisor1, 1),
count(uniqueCnt2, divisor2, 1),
count(uniqueCnt1+uniqueCnt2, divisor1, divisor2))
# Time: O(log(min(d1, d2)) + logr)
# Space: O(1)
# binary search
class Solution2(object):
def minimizeSet(self, divisor1, divisor2, uniqueCnt1, uniqueCnt2):
"""
:type divisor1: int
:type divisor2: int
:type uniqueCnt1: int
:type uniqueCnt2: int
:rtype: int
"""
def gcd(a, b):
while b:
a, b = b, a%b
return a
def lcm(a, b):
return a//gcd(a, b)*b
def check(cnt):
return (cnt-cnt//divisor1 >= uniqueCnt1 and
cnt-cnt//divisor2 >= uniqueCnt2 and
cnt-cnt//l >= uniqueCnt1+uniqueCnt2)
l = lcm(divisor1, divisor2)
left, right = 2, 2**31-1
while left <= right:
mid = left+(right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left