Problem Description
Given an array of intervals where each interval is represented as [l, r, weight] (with l and r defining the start and end positions, and weight being a positive integer), choose at most 4 intervals that do not overlap (note that even sharing a boundary counts as overlapping) so that the total weight is maximized. If there are multiple sets with the same maximum total weight, return the lexicographically smallest list of their original indices.
Key Insights
- Since the number of intervals chosen is small (at most 4), a dynamic programming solution where the state includes the count of intervals selected is feasible.
- Sorting intervals (for example, by their ending times) allows efficient binary search to find the previous non-overlapping interval.
- Use binary search (or bisect) to quickly locate the rightmost interval whose end is strictly less than the current interval’s start.
- DP state should capture both the maximum score and the chosen set (as a list of original indices) to later decide lexicographic order if scores are equal.
- When combining solutions, always sort the candidate’s indices so that lexicographical comparison is done with their sorted order.
Space and Time Complexity
Time Complexity: O(4 * N * log N) where N is the number of intervals (binary search per DP update for 4 levels). Space Complexity: O(4 * N) storing DP states, each containing a score and list of indices.
Solution
We first sort the intervals by ending time while preserving their original indices. For each interval we can decide whether to take it or not, maintaining a DP table where dp[k][i] represents the best solution (maximum score and chosen index set) obtainable by considering the first i intervals and taking exactly k intervals.
To update dp[k][i], we have two choices:
- Not picking the current interval, so dp[k][i] = dp[k][i-1].
- Picking the current interval; then use binary search to find the rightmost interval j that ends strictly before the current interval’s start, and combine dp[k-1][j+1] with the current interval’s weight and original index.
When the candidate solutions have equal scores, we choose the one whose sorted list of indices is lexicographically smaller. Finally, since we can choose any number up to 4 intervals, we take the best among the DP solutions for 1, 2, 3, or 4 intervals.