#3414

Maximum Score of Non-overlapping Intervals

Hard
ArrayBinary SearchDynamic ProgrammingSortingDynamic ProgrammingSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

By sorting the intervals by their end times and using dynamic programming, we can efficiently find the maximum score of non-overlapping intervals. This approach allows us to build solutions incrementally and avoid unnecessary checks.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the intervals based on their end times.
  2. 2Step 2: Use a dynamic programming array to store the maximum score achievable up to each interval.
  3. 3Step 3: For each interval, check previous intervals to find the last non-overlapping interval and update the DP array accordingly.
  4. 4Step 4: Track the indices of the intervals chosen to reconstruct the solution.
solution.py19 lines
1def maxScoreIntervals(intervals):
2    intervals.sort(key=lambda x: x[1])
3    n = len(intervals)
4    dp = [0] * n
5    prev = [-1] * n
6    for i in range(n):
7        dp[i] = intervals[i][2]
8        for j in range(i):
9            if intervals[j][1] <= intervals[i][0]:
10                if dp[j] + intervals[i][2] > dp[i]:
11                    dp[i] = dp[j] + intervals[i][2]
12                    prev[i] = j
13    max_score = max(dp)
14    index = dp.index(max_score)
15    result = []
16    while index != -1:
17        result.append(intervals[index][0])
18        index = prev[index]
19    return sorted(result)

Complexity note: The complexity is O(n log n) due to the sorting step, and O(n) for the dynamic programming array and previous index tracking.

  • 1Sorting intervals by their end times helps in efficiently finding non-overlapping intervals.
  • 2Dynamic programming allows us to build solutions incrementally, avoiding redundant checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.