Maximum length intersection of all K ranges among all given ranges
Last Updated : 28 Mar, 2023
Given an array arr[] consisting of N ranges of the form [L, R], the task is to select K ranges such that the intersection length of the K ranges is maximum.
Examples:
Input: arr[] = {{5, 15}, {1, 10}, {14, 50}, {30, 70}, {99, 100}}, K = 2 Output: 21 Explanation: Selecting ranges (14, 50) and (30, 70) would give the maximum answer. Therefore, the maximum length intersection of above 2 ranges is (50 - 30 + 1) = 21.
Output: 5 Explanation: Selecting ranges (1, 10), (3, 7), (3, 10), which will give us the maximum length possible.
Approach: The problem can be solved based on the following idea:
Sorting ranges according to { L, R } and considering each given range as a potential starting point L to our required answer as [L, Kth largest ending point of ranges seen so far].
Follow the steps mentioned below to implement the idea:
Use vector pair asc to store ranges in non-decreasing order of starting point l followed by ending point r.
Traverse asc from the beginning and maintain min-heap (priority_queue) pq to store K largest ending point r of ranges seen so far.
Discard the values from the heap if it is less than the starting point l[i] of the current range i.
Update the answer as the maximum of previous answers we got and pq.top() - l[i] + 1.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach#include<bits/stdc++.h>usingnamespacestd;// Function to get maximum// intersection lengthintmaxKRanges(vector<vector<int>>range,intk){intn=range.size();vector<pair<int,int>>asc;for(inti=0;i<n;i++){asc.push_back({range[i][0],range[i][1]});}// Sorting ranges in// non-descending ordersort(asc.begin(),asc.end());// Min-heap to store k largest ending// point of ranges seen so farpriority_queue<int,vector<int>,greater<int>>pq;intans=0;for(inti=0;i<n;i++){// Ending point of ith rangepq.push(asc[i].second);// Ranges having zero intersectionwhile(!pq.empty()&&pq.top()<asc[i].first)pq.pop();// Size upto kwhile(pq.size()>k)pq.pop();// Update answerif(pq.size()==k)ans=max(ans,pq.top()-asc[i].first+1);}returnans;}// Driver Codeintmain(){// Number of rangesintN=5;// Number of ranges selected at a timeintK=2;vector<vector<int>>range={{5,15},{1,10},{14,50},{30,70},{99,100}};// Function callcout<<maxKRanges(range,K)<<endl;return0;}
Python3
# Python code to implement the approachimportheapq# Function to get maximum# intersection lengthdefmaxKRanges(range_,k):n=len(range_)asc=[]foriinrange(n):asc.append((range_[i][0],range_[i][1]))# Sorting ranges in# non-descending orderasc.sort()# Min-heap to store k largest ending# point of ranges seen so farpq=[]ans=0foriinrange(n):# Ending point of ith rangeheapq.heappush(pq,asc[i][1])# Ranges having zero intersectionwhilepqandpq[0]<asc[i][0]:heapq.heappop(pq)# Size upto kwhilelen(pq)>k:heapq.heappop(pq)# Update answeriflen(pq)==k:ans=max(ans,pq[0]-asc[i][0]+1)returnans# Driver Code# Number of rangesN=5# Number of ranges selected at a timeK=2range_=[[5,15],[1,10],[14,50],[30,70],[99,100]]# Function callprint(maxKRanges(range_,K))
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classProgram{staticintMaxKRanges(List<List<int>>range,intk){intn=range.Count;List<Tuple<int,int>>asc=newList<Tuple<int,int>>();for(inti=0;i<n;i++){asc.Add(newTuple<int,int>(range[i][0],range[i][1]));}// Sorting ranges in non-descending orderasc.Sort();// SortedSet to store k largest ending point of ranges seen so farSortedSet<int>pq=newSortedSet<int>();intans=0;for(inti=0;i<n;i++){// Ending point of ith rangepq.Add(asc[i].Item2);// Ranges having zero intersectionwhile(pq.Count>0&&pq.Min<asc[i].Item1)pq.Remove(pq.Min);// Size upto kwhile(pq.Count>k)pq.Remove(pq.Max);// Update answerif(pq.Count==k)ans=Math.Max(ans,pq.Min-asc[i].Item1+1);}returnans;}// Driver CodestaticvoidMain(){// Number of rangesintN=5;// Number of ranges selected at a timeintK=2;List<List<int>>range=newList<List<int>>(){newList<int>(){5,15},newList<int>(){1,10},newList<int>(){14,50},newList<int>(){30,70},newList<int>(){99,100}};// Function callConsole.WriteLine(MaxKRanges(range,K));}}
JavaScript
// Function to get maximum intersection lengthfunctionmaxKRanges(range,k){constn=range.length;constasc=[];for(leti=0;i<n;i++){asc.push([range[i][0],range[i][1]]);}// Sorting ranges in non-descending orderasc.sort((a,b)=>a[0]-b[0]);// Min-heap to store k largest ending// point of ranges seen so farconstpq=[];letans=0;for(leti=0;i<n;i++){// Ending point of ith rangepq.push(asc[i][1]);// Ranges having zero intersectionwhile(pq.length&&pq[0]<asc[i][0]){pq.shift();}// Size upto kwhile(pq.length>k){pq.shift();}// Update answerif(pq.length===k){ans=Math.max(ans,pq[0]-asc[i][0]+1);}}returnans;}// Driver code// Number of rangesconstN=5;// Number of ranges selected at a timeconstK=2;constrange=[[5,15],[1,10],[14,50],[30,70],[99,100]];// Function callconsole.log(maxKRanges(range,K));// This code is contributed by Prajwal Kandekar
Java
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collections;importjava.util.PriorityQueue;classGFG{publicstaticintmaxKRanges(ArrayList<ArrayList<Integer>>range,intk){intn=range.size();int[][]asc=newint[n][2];for(inti=0;i<n;i++){asc[i][0]=range.get(i).get(0);asc[i][1]=range.get(i).get(1);}// Sorting ranges in non-descending orderArrays.sort(asc,(a,b)->a[0]-b[0]);// Min-heap to store k largest ending point of ranges seen so farPriorityQueue<Integer>pq=newPriorityQueue<>(k);intans=0;for(inti=0;i<n;i++){// Ending point of ith rangepq.offer(asc[i][1]);// Ranges having zero intersectionwhile(!pq.isEmpty()&&pq.peek()<asc[i][0])pq.poll();// Size up to kwhile(pq.size()>k)pq.poll();// Update answerif(pq.size()==k)ans=Math.max(ans,pq.peek()-asc[i][0]+1);}returnans;}publicstaticvoidmain(String[]args){// Number of rangesintN=5;// Number of ranges selected at a timeintK=2;ArrayList<ArrayList<Integer>>range=newArrayList<>();range.add(newArrayList<Integer>(Arrays.asList(5,15)));range.add(newArrayList<Integer>(Arrays.asList(1,10)));range.add(newArrayList<Integer>(Arrays.asList(14,50)));range.add(newArrayList<Integer>(Arrays.asList(30,70)));range.add(newArrayList<Integer>(Arrays.asList(99,100)));// Function callSystem.out.println(maxKRanges(range,K));}}
Output
21
Time Complexity: O(N * log(N)) Auxiliary Space: O(N)