-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
find-subarray-with-bitwise-or-closest-to-k.py
75 lines (66 loc) · 1.84 KB
/
find-subarray-with-bitwise-or-closest-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
63
64
65
66
67
68
69
70
71
72
73
74
75
# Time: O(nlogr), r = max(nums)
# Space: O(logr)
# freq table, two pointers, sliding window, lc1521
class BitCount(object):
def __init__(self, n):
self.__l = 0
self.__n = n
self.__count = [0]*n
def __iadd__(self, num):
self.__l += 1
base = 1
for i in xrange(self.__n):
if num&base:
self.__count[i] += 1
base <<= 1
return self
def __isub__(self, num):
self.__l -= 1
base = 1
for i in xrange(self.__n):
if num&base:
self.__count[i] -= 1
base <<= 1
return self
def bit_or(self):
num, base = 0, 1
for i in xrange(self.__n):
if self.__count[i]:
num |= base
base <<= 1
return num
class Solution(object):
def minimumDifference(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
count = BitCount(max(nums).bit_length())
result, left = float("inf"), 0
for right in xrange(len(nums)):
count += nums[right]
while left <= right:
f = count.bit_or()
result = min(result, abs(f-k))
if f <= k:
break
count -= nums[left]
left += 1
return result
# Time: O(nlogr), r = max(nums)
# Space: O(logr)
# dp, lc1521
class Solution2(object):
def minimumDifference(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
result, dp = float("inf"), set() # at most O(logr) dp states
for x in nums:
dp = {x}|{f|x for f in dp}
for f in dp:
result = min(result, abs(f-k))
return result