Maximum sum of at most two non-overlapping intervals in a list of Intervals | Interval Scheduling Problem
Last Updated :
31 Jan, 2023
Given an array interval of length N, where each element represents three values, i.e. {startTime, endTime, value}. The task is to find the maximum sum of values of at most two non-overlapping intervals.
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.
Approach: This problem can be solved with the help of a priority queue. To solve this problem, follow the below steps:
- 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.
- Store the pair of {endTime, value} in the priority queue and sort on the basis of endTime.
- 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.
- Now, update the ans, after each traversal as, ans= Math.max(ans, max + interval[i][2]).
- Return ans as the final answer to this problem.
Below is the implementation of the above approach
C++
#include <bits/stdc++.h>
using namespace std;
int maxTwoNonOverLapping(vector<vector< int > >& interval)
{
sort(interval.begin(), interval.end(),
[](vector< int >& a, vector< int >& b) {
return (a[0] == b[0]) ? a[1] < b[1]
: a[0] < b[0];
});
priority_queue<vector< int > > pq;
int ma = 0;
int ans = 0;
for ( auto e : interval) {
while (!pq.empty()) {
if (pq.top()[0] >= e[0])
break ;
vector< int > qu = pq.top();
pq.pop();
ma = max(ma, qu[1]);
}
ans = max(ans, ma + e[2]);
pq.push({ e[1], e[2] });
}
return ans;
}
int main()
{
vector<vector< int > > interval
= { { 1, 3, 2 }, { 4, 5, 2 }, { 1, 5, 5 } };
int maxValue = maxTwoNonOverLapping(interval);
cout << maxValue;
return 0;
}
|
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
int [][] interval
= { { 1 , 3 , 2 }, { 4 , 5 , 2 }, { 1 , 5 , 5 } };
int maxValue = maxTwoNonOverLapping(interval);
System.out.println(maxValue);
}
public static int maxTwoNonOverLapping( int [][] interval)
{
Arrays.sort(interval,
(a, b)
-> (a[ 0 ] == b[ 0 ]) ? a[ 1 ] - b[ 1 ]
: a[ 0 ] - b[ 0 ]);
PriorityQueue< int []> pq
= new PriorityQueue<>((a, b) -> a[ 0 ] - b[ 0 ]);
int max = 0 ;
int ans = 0 ;
for ( int [] e : interval) {
while (!pq.isEmpty()) {
if (pq.peek()[ 0 ] >= e[ 0 ])
break ;
int [] qu = pq.remove();
max = Math.max(max, qu[ 1 ]);
}
ans = Math.max(ans, max + e[ 2 ]);
pq.add( new int [] { e[ 1 ], e[ 2 ] });
}
return ans;
}
}
|
Python3
from queue import PriorityQueue
def maxTwoNonOverLapping(interval):
interval.sort()
pq = PriorityQueue()
ma = 0 ;
ans = 0
for e in interval:
while not pq.empty():
if (pq.queue[ 0 ][ 0 ] > = e[ 0 ]):
break ;
qu = pq.get();
ma = max (ma, qu[ 1 ]);
ans = max (ans, ma + e[ 2 ]);
pq.put([ e[ 1 ], e[ 2 ] ]);
return ans;
if __name__ = = '__main__' :
interval = [ [ 1 , 3 , 2 ], [ 4 , 5 , 2 ], [ 1 , 5 , 5 ] ];
maxValue = maxTwoNonOverLapping(interval);
print (maxValue);
|
C#
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
public static void Main( string [] args)
{
int [][] interval = new int [][] {
new int [] { 1, 3, 2 },
new int [] { 4, 5, 2 },
new int [] { 1, 5, 5 }
};
int maxValue = maxTwoNonOverLapping(interval);
Console.WriteLine(maxValue);
}
public static int maxTwoNonOverLapping( int [][] interval)
{
var sorted = interval.OrderBy(a => a[0]).ThenBy(a => a[1]);
interval = sorted.ToArray();
SortedSet< int []> pq = new SortedSet< int []>(Comparer< int []>.Create((a, b) => a[0].CompareTo(b[0])));
int max = 0;
int ans = 0;
foreach ( int [] e in interval) {
while (pq.Count > 0) {
if (pq.First()[0] >= e[0])
break ;
int [] qu = pq.First();
pq.Remove(qu);
max = Math.Max(max, qu[1]);
}
ans = Math.Max(ans, max + e[2]);
pq.Add( new int [] { e[1], e[2] });
}
return ans;
}
}
|
Javascript
<script>
function maxTwoNonOverLapping(interval){
interval.sort();
pq = [];
ma = 0;
ans = 0
for (let i=0;i<interval.length;i++){
e=interval[i];
while (pq.length){
if (pq[0][0] >= e[0]){
break ;
}
qu = pq[0];
pq.pop(0);
ma = Math.max(ma, qu[1]);
}
ans = Math.max(ans, ma + e[2]);
pq.push([ e[1], e[2] ]);
pq.sort();
}
return ans;
}
let interval = [ [ 1, 3, 2 ], [ 4, 5, 2 ], [ 1, 5, 5 ] ];
let maxValue = maxTwoNonOverLapping(interval);
document.write(maxValue);
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...