Maximum Score of Non-overlapping Intervals - Problem

You are given a 2D integer array intervals, where intervals[i] = [li, ri, weighti]. Interval i starts at position li and ends at ri, and has a weight of weighti.

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.

Note: 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.

Input & Output

Example 1 — Basic Case
$ Input: intervals = [[1,3,2],[2,4,3],[3,5,1]]
Output: [1]
💡 Note: We can only choose one interval due to overlaps. Interval at index 1 has weight 3, which is the maximum. So we return [1].
Example 2 — Non-overlapping Intervals
$ Input: intervals = [[1,2,1],[3,4,2],[5,6,3]]
Output: [0,1,2]
💡 Note: All intervals are non-overlapping. We can take all three: indices [0,1,2] with total weight 1+2+3=6.
Example 3 — Choose Best Combination
$ Input: intervals = [[1,3,2],[2,5,3],[4,6,1],[7,8,4]]
Output: [0,2,3]
💡 Note: Best non-overlapping combination: intervals 0 [1,3], 2 [4,6], and 3 [7,8] with total weight 2+1+4=7.

Constraints

  • 1 ≤ intervals.length ≤ 104
  • intervals[i].length == 3
  • 1 ≤ li ≤ ri ≤ 109
  • 1 ≤ weighti ≤ 106

Visualization

Tap to expand
Maximum Score of Non-overlapping Intervals INPUT intervals = [[1,3,2],[2,4,3],[3,5,1]] 1 2 3 4 5 i=0, w=2 i=1, w=3 i=2, w=1 Legend: [1,3] weight=2 [2,4] weight=3 [3,5] weight=1 Choose up to 4 non-overlapping intervals for max score ALGORITHM (DP) 1 Sort by end time Order intervals for DP 2 DP State: dp[i][k] Max score using i intervals, choosing up to k (max 4) 3 Binary Search Find last non-overlapping interval for each choice 4 Track Indices Keep lex smallest indices with max score Score Comparison: i=1: score=3 i=0: score=2 i=2: score=1 FINAL RESULT Best Choice: Interval 1 1 2 3 4 [2,4] w=3 Output: [1] Max Score = 3 Using interval at index 1 OK Lexicographically smallest Key Insight: DP with binary search finds optimal non-overlapping intervals. State dp[i][k] tracks max score considering first i intervals, choosing up to k. Binary search finds the last compatible interval efficiently. Track indices throughout to ensure lexicographically smallest result with max score. TutorialsPoint - Maximum Score of Non-overlapping Intervals | DP Approach
Asked in
Google 15 Facebook 12 Amazon 10
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen