// C# program for the above approach
using System;
public class GFG
{
// Function to find the segment which
// overlaps with maximum number of segments
static void maxIntersection(int [,]segments, int N)
{
// 'L' & 'R' co-ordinates of all
// segments are stored in lvalues & rvalues
int []rvalues = new int[N];
int []lvalues = new int[N];
// Assign co-ordinates
for (int i = 0; i < N; ++i)
{
lvalues[i] = segments[i,0];
rvalues[i] = segments[i,1];
}
// Co-ordinate compression
Array.Sort(lvalues);
Array.Sort(rvalues);
// Stores the required segment
int []answer = { -1, -1 };
// Stores the current maximum
// number of intersections
int numIntersections = 0;
for (int i = 0; i < N; ++i)
{
// Find number of 'R' coordinates
// which are less than the 'L'
// value of the current segment
int lesser
= lower_bound(rvalues, 0,
segments.GetLength(0),
segments[i,0]);
// Find number of 'L' coordinates
// which are greater than the 'R'
// value of the current segment
int greater = Math.Max(
0, N-(upper_bound(lvalues, 0,
segments.GetLength(0),
segments[i,1])));
// Segments excluding 'lesser' and
// 'greater' gives the number of
// intersections
if ((N - lesser - greater) >= numIntersections) {
answer = new int[]{ segments[i,0], segments[i,1] };
// Update the current maximum
numIntersections = (N - lesser - greater);
}
}
// Print segment coordinates
Console.Write(answer[0]+ " " + answer[1]);
}
static int lower_bound(int[] a, int low,
int high, int element)
{
while(low < high)
{
int middle = low + (high - low)/2;
if(element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
static int upper_bound(int[] a, int low,
int high, int element)
{
while(low < high)
{
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
// Driver Code
public static void Main(String[] args)
{
// Given segments
int [,]segments = { { 1, 4 }, { 2, 3 }, { 3, 6 } };
// Size of segments array
int N = segments.GetLength(0);
maxIntersection(segments, N);
}
}
// This code is contributed by shikhasingrajput