-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
maximum-score-of-non-overlapping-intervals.py
57 lines (50 loc) · 1.94 KB
/
maximum-score-of-non-overlapping-intervals.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
# Time: O(nlogn + n * k^2)
# Space: O(n * k^2)
import bisect
# dp, binary search
class Solution(object):
def maximumWeight(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[int]
"""
K = 4
lookup = {}
for i, (l, r, w) in enumerate(intervals):
if (r, l, w) not in lookup:
lookup[r, l, w] = i
sorted_intervals = sorted(lookup.iterkeys(), key=lambda x: x[0])
dp = [[[0, []] for _ in xrange(K+1)] for _ in xrange(len(sorted_intervals)+1)]
for i in xrange(len(dp)-1):
j = bisect.bisect_right(sorted_intervals, (sorted_intervals[i][1], 0, 0))-1
idx = lookup[sorted_intervals[i]]
for k in xrange(1, len(dp[i])):
new_dp = [dp[j+1][k-1][0]-sorted_intervals[i][2], dp[j+1][k-1][1][:]]
insort(new_dp[1], idx)
dp[i+1][k] = min(dp[i][k], new_dp)
return dp[len(sorted_intervals)][K][1]
# Time: O(nlogn + n * k^2)
# Space: O(n * k^2)
import bisect
# dp, binary search
class Solution2(object):
def maximumWeight(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[int]
"""
K = 4
lookup = {}
for i, (l, r, w) in enumerate(intervals):
if (l, r, w) not in lookup:
lookup[l, r, w] = i
sorted_intervals = sorted(lookup.iterkeys(), key=lambda x: x[0])
dp = [[[0, []] for _ in xrange(K+1)] for _ in xrange(len(sorted_intervals)+1)]
for i in reversed(xrange(len(dp)-1)):
j = bisect.bisect_right(sorted_intervals, (sorted_intervals[i][1]+1, 0, 0))
idx = lookup[sorted_intervals[i]]
for k in xrange(1, len(dp[i])):
new_dp = [dp[j][k-1][0]-sorted_intervals[i][2], dp[j][k-1][1][:]]
insort(new_dp[1], idx)
dp[i][k] = min(dp[i+1][k], new_dp)
return dp[0][K][1]