Given two parallel lines of length N and an array containing total N endpoints in array EndPoints. Given that there is a straight line from each i, such that 1 <= i <= N, such that each line should end at any of the EndPoint[j]. The task is to get the count of maximum number of intersections from the lines.
Notice: There should be a total of n lines drawn and every endpoint given in the array should be covered.
As you can see in the diagram above, a line is drawn from each i (1, 2, 3, 4, 5, 6, 7) and the endpoint is one of the values from EndPoints given in the input. It can be proven that there can not be more than 6 intersections in this case.
Maximum Intersection Possible: 6
Maximum Intersection Possible: 2
Maximum Intersection Possible: 5
Time Complexity: O(N2) Auxiliary Space: O(1)
The Basic idea is to use onset template policy based data structure and count frequency of duplicate elements and perform respective operations.
The above approach can also be optimized if are able to count the number of pairs (i,j) such that ai≥aj in an efficient manner.
The ordered set keeps the unique elements in sorted order and provides a number of items strictly smaller than k, which is required in this problem.
order_of_key(k) : Number of items strictly smaller than k .
Thus, we can loop over the input array and add each element one by one and can check order_of_key(element) at each iteration to get the number of elements less than the element and add that to our sum.
we will have to count the running frequency of each element because we know that equal elements also intersect each other, thus we will be adding the running frequencies to our answer as well.
Below is the Implementation of the above approach:
// Important header files
#include <ext/pb_ds/assoc_container.hpp> // Common file
#include <functional> // for less
// defining required namespaces for policy based data
Please Login to comment...