Skip to content

Commit 4777142

Browse files
authored
Create earliest-second-to-mark-indices-ii.py
1 parent 313024e commit 4777142

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O((m + nlogn) * logm)
2+
# Space: O(n)
3+
4+
import heapq
5+
6+
7+
# binary search, greedy, heap
8+
class Solution(object):
9+
def earliestSecondToMarkIndices(self, nums, changeIndices):
10+
"""
11+
:type nums: List[int]
12+
:type changeIndices: List[int]
13+
:rtype: int
14+
"""
15+
def check(t):
16+
min_heap = []
17+
cnt = 0
18+
for i in reversed(xrange(t)):
19+
if i != lookup[changeIndices[i]-1]:
20+
cnt += 1
21+
continue
22+
heapq.heappush(min_heap, nums[changeIndices[i]-1])
23+
if cnt:
24+
cnt -= 1
25+
else:
26+
cnt += 1
27+
heapq.heappop(min_heap)
28+
return total-(sum(min_heap)+len(min_heap)) <= cnt
29+
30+
lookup = [-1]*len(nums)
31+
for i in reversed(xrange(len(changeIndices))):
32+
if nums[changeIndices[i]-1]:
33+
lookup[changeIndices[i]-1] = i
34+
total = sum(nums)+len(nums)
35+
left, right = sum((1 if lookup[i] != -1 else nums[i]) for i in xrange(len(nums)))+len(nums), len(changeIndices)
36+
while left <= right:
37+
mid = left+(right-left)//2
38+
if check(mid):
39+
right = mid-1
40+
else:
41+
left = mid+1
42+
return left if left <= len(changeIndices) else -1

0 commit comments

Comments
 (0)