Maximum Score of Non-overlapping Intervals Problem
Description
LeetCode Problem 3414.
You are given a 2D integer array intervals, where intervals[i] = [l_i, r_i, weight_i]. Interval i starts at position l_i and ends at r_i, and has a weight of weight_i. You can choose up to 4 non-overlapping intervals. The score of the chosen intervals is defined as the total sum of their weights.
Return the lexicographically smallest array of at most 4 indices from intervals with maximum score, representing your choice of non-overlapping intervals.
Two intervals are said to be non-overlapping if they do not share any points. In particular, intervals sharing a left or right boundary are considered overlapping.
Example 1:
Input: intervals = [[1,3,2],[4,5,2],[1,5,5],[6,9,3],[6,7,1],[8,9,1]]
Output: [2,3]
Explanation:
You can choose the intervals with indices 2, and 3 with respective weights of 5, and 3.
Example 2:
Input: intervals = [[5,8,1],[6,7,7],[4,7,3],[9,10,6],[7,8,2],[11,14,3],[3,5,5]]
Output: [1,3,5,6]
Explanation:
You can choose the intervals with indices 1, 3, 5, and 6 with respective weights of 7, 6, 3, and 5.
Constraints:
1 <= intevals.length <= 5 * 10^4intervals[i].length == 3intervals[i] = [l_i, r_i, weight_i]1 <= l_i <= r_i <= 10^91 <= weight_i <= 10^9
Solution
Approach: Sorting + Binary Search + DP
Sort the intervals by left end (remembering their original indexes). For each interval i, binary search nxt[i], the first interval that starts strictly after i ends. Intervals that share an endpoint overlap, so they cannot both be chosen.
Let f[i][k] be the best total weight using intervals i, i+1, ... with at most k picks, and g[i][k] the lexicographically smallest list of original indexes that reaches it. Going from the back, we either skip interval i (take f[i+1][k]) or take it (add its weight to f[nxt[i]][k-1] and insert its index into the sorted list g[nxt[i]][k-1]). We keep the larger weight and, on a tie, the smaller list. The answer is g[0][4].
Complexity: O(n log n) time and O(n) space. The lists never hold more than 4 indexes, so inserting and comparing them takes constant time.
class Solution:
def maximumWeight(self, intervals: List[List[int]]) -> List[int]:
n = len(intervals)
arr = [[e[0], e[1], e[2], i] for i, e in enumerate(intervals)]
arr.sort()
nxt = [0] * n
for i in range(n):
l, r = i + 1, n
while l < r:
mid = (l + r) >> 1
if arr[mid][0] > arr[i][1]:
r = mid
else:
l = mid + 1
nxt[i] = l
f = [[0] * 5 for _ in range(n + 1)]
g = [[[] for _ in range(5)] for _ in range(n + 1)]
for i in range(n - 1, -1, -1):
for k in range(1, 5):
s1, a1 = f[i + 1][k], g[i + 1][k]
a2 = g[nxt[i]][k - 1][:]
x = arr[i][3]
j = 0
while j < len(a2) and a2[j] < x:
j += 1
a2.insert(j, x)
s2 = f[nxt[i]][k - 1] + arr[i][2]
if s2 > s1 or (s2 == s1 and a2 < a1):
f[i][k] = s2
g[i][k] = a2
else:
f[i][k] = s1
g[i][k] = a1
return g[0][4]