forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-white-tiles-covered-by-a-carpet.py
99 lines (88 loc) · 2.87 KB
/
maximum-white-tiles-covered-by-a-carpet.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# Time: O(nlogn)
# Space: O(1)
# sliding window, optimized from solution3
class Solution(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
result = right = gap = 0
for left, (l, _) in enumerate(tiles):
if left-1 >= 0:
gap -= tiles[left][0]-tiles[left-1][1]-1
r = l+carpetLen-1
while right+1 < len(tiles) and r+1 >= tiles[right+1][0]:
right += 1
gap += tiles[right][0]-tiles[right-1][1]-1
result = max(result, min(tiles[right][1]-tiles[left][0]+1, carpetLen)-gap)
return result
# Time: O(nlogn)
# Space: O(1)
# sliding window, optimized from solution4
class Solution2(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
result = left = gap = 0
for right in xrange(len(tiles)):
if right-1 >= 0:
gap += tiles[right][0]-tiles[right-1][1]-1
l = tiles[right][1]-carpetLen+1
while not (tiles[left][1]+1 >= l):
left += 1
gap -= tiles[left][0]-tiles[left-1][1]-1
result = max(result, min(tiles[right][1]-tiles[left][0]+1, carpetLen)-gap)
return result
# Time: O(nlogn)
# Space: O(n)
import bisect
# prefix sum, binary search
class Solution3(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
prefix = [0]*(len(tiles)+1)
for i, (l, r) in enumerate(tiles):
prefix[i+1] = prefix[i]+(r-l+1)
result = 0
for left, (l, _) in enumerate(tiles):
r = l+carpetLen-1
right = bisect.bisect_right(tiles, [r+1])-1
extra = max(tiles[right][1]-r, 0)
result = max(result, (prefix[right+1]-prefix[left])-extra)
return result
# Time: O(nlogn)
# Space: O(n)
import bisect
# prefix sum, binary search
class Solution4(object):
def maximumWhiteTiles(self, tiles, carpetLen):
"""
:type tiles: List[List[int]]
:type carpetLen: int
:rtype: int
"""
tiles.sort()
prefix = [0]*(len(tiles)+1)
for i, (l, r) in enumerate(tiles):
prefix[i+1] = prefix[i]+(r-l+1)
result = 0
for right, (_, r) in enumerate(tiles):
l = r-carpetLen+1
left = bisect.bisect_right(tiles, [l])
if left-1 >= 0 and tiles[left-1][1]+1 >= l:
left -= 1
extra = max(l-tiles[left][0], 0)
result = max(result, (prefix[right+1]-prefix[left])-extra)
return result