-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
number-of-subarrays-with-lcm-equal-to-k.py
62 lines (53 loc) · 1.32 KB
/
number-of-subarrays-with-lcm-equal-to-k.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
# Time: O(n * sqrt(k) * logk)
# Space: O(sqrt(k))
import collections
# dp
class Solution(object):
def subarrayLCM(self, nums, k):
"""
:type nums: List[int]
:type k: 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
result = 0
dp = collections.Counter()
for x in nums:
new_dp = collections.Counter()
if k%x == 0:
dp[x] += 1
for l, cnt in dp.iteritems():
new_dp[lcm(l, x)] += cnt
dp = new_dp
result += dp[k]
return result
# Time: O(n^2)
# Space: O(1)
# brute force
class Solution2(object):
def subarrayLCM(self, nums, k):
"""
:type nums: List[int]
:type k: 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
result = 0
for i in xrange(len(nums)):
l = 1
for j in xrange(i, len(nums)):
if k%nums[j]:
break
l = lcm(l, nums[j])
result += int(l == k)
return result