-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-number-of-potholes-that-can-be-fixed.py
75 lines (71 loc) · 2.01 KB
/
maximum-number-of-potholes-that-can-be-fixed.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(n)
# Space: O(n)
# counting sort, greedy
class Solution(object):
def maxPotholes(self, road, budget):
"""
:type road: str
:type budget: int
:rtype: int
"""
def inplace_counting_sort(nums, reverse=False): # Time: O(n)
if not nums:
return
count = [0]*(max(nums)+1)
for num in nums:
count[num] += 1
for i in xrange(1, len(count)):
count[i] += count[i-1]
for i in reversed(xrange(len(nums))): # inplace but unstable sort
while nums[i] >= 0:
count[nums[i]] -= 1
j = count[nums[i]]
nums[i], nums[j] = nums[j], ~nums[i]
for i in xrange(len(nums)):
nums[i] = ~nums[i] # restore values
if reverse: # unstable sort
nums.reverse()
ls = []
l = 0
for i in xrange(len(road)):
l += 1
if i+1 == len(road) or road[i+1] != road[i]:
if road[i] == 'x':
ls.append(l)
l = 0
inplace_counting_sort(ls)
result = 0
for l in reversed(ls):
c = min(l+1, budget)
if c-1 <= 0:
break
result += c-1
budget -= c
return result
# Time: O(nlogn)
# Space: O(n)
# sort, greedy
class Solution2(object):
def maxPotholes(self, road, budget):
"""
:type road: str
:type budget: int
:rtype: int
"""
ls = []
l = 0
for i in xrange(len(road)):
l += 1
if i+1 == len(road) or road[i+1] != road[i]:
if road[i] == 'x':
ls.append(l)
l = 0
ls.sort()
result = 0
for l in reversed(ls):
c = min(l+1, budget)
if c-1 <= 0:
break
result += c-1
budget -= c
return result