VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-of-at-most-two-non-overlapping-intervals-in-a-list-of-intervals-interval-scheduling-problem/

⇱ Max Sum of At Most Two Non-Overlapping Intervals - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Max Sum of At Most Two Non-Overlapping Intervals

Last Updated : 12 Nov, 2025

Given an array interval[] , where each element represents the following three values

  • startTime – the time when the interval begins
  • endTime – the time when the interval ends
  • value – the value associated with this interval

Find the maximum sum of values by selecting at most two intervals that do not overlap.

Example: 

Input: interval[] = [[1, 3, 2], [4, 5, 2], [2, 4, 3]]
Output: 4
Explanation: Select interval 1 and 2 (as third interval is overlapping). Therefore, maximum value is 2 + 2 = 4.

Input: interval[] = [[1, 3, 2], [4, 5, 2], [1, 5, 5]]
Output: 5
Explanation: As intervals 1 and 2 are non-overlapping but their value will be 2 + 2 = 4. So, instead of 1 and 2, only 3 can be selected with a value of 5.

[Naive Approach] - O(n2) Time and O(1) Space

For each interval (or pair of intervals), we calculate the sum of their values only if they do not overlap and keep track of the maximum sum found so far. We also consider the case where a single interval alone provides the maximum value.

[Expected Approach]Using Priority Queue - O(n x logn) Time and O(n) Space

This problem can be solved with the help of a priority queue. To solve this problem, follow the below steps:

  1. Sort the given array interval w.r.t. startTime. If startTime of two intervals are the same then sort it on the basis of endTime.
  2. Store the pair of {endTime, value} in the priority queue ordered on the basis of endTime.
  3. Traverse the given array and calculate the maximum value for all events whose endTime is smaller than the startTime of the present interval and store it in variable max.
  4. Now, update the ans, after each traversal as, ans= Math.max(ans, max + interval[i][2]).
  5. Return ans as the final answer to this problem.

 Below is the implementation of the above approach


Output
5
Comment