Connecting Ropes
Ninja visited his village after a long time. His village is having a river in its center with ‘N’ houses on the northern bank with distinct X-coordinates ‘A[1]’ , A[2]’ , … , ‘A[N]’ and ‘N’ houses on the southern bank with distinct X-coordinates ‘B[1]’ , ‘B[2]’ , …, ‘B[N]’.
Ninja aims to connect as many north-south pairs of houses with ropes as possible such that no ropes cross each other. He will only connect house ‘A[i]’ with house ‘B[i]’.
Given an integer ‘N’ and arrays ‘A’ and ‘B’ representing the coordinates of houses. Find the maximum number of pairs of houses Ninja can connect.
Example :
N = 3
A = [ 1, 2, 3 ]
B = [ 2, 1, 3 ]
Explanation :
One of the possible connections can be (1,2) and (3,3).
Another possible connection is (2,1) and (3,3).
Ninja cannot connect all 3 pairs (1,2) , (2,1) and (3,3) as the first 2 pairs cross each other.
So, the maximum connection is 2.
Input Format :
The first line contains an integer 'T' which denotes the number of test cases to be run. Then the test cases follow.
The first line of each test case contains an integer ‘N’.
The next line contains ‘N’ integers representing the elements of array ‘A’ which denotes the coordinates of the northern houses.
The next line contains ‘N’ integers representing the elements of array ‘B’ which denotes the coordinates of the southern houses.
Output format :
For each test case, output an integer denoting the maximum connections of houses possible.
Print the output of each test case in a new line.
Note :
You don’t need to print anything. It has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 5
1 <= N <= 10^5
1 <= A[i] <= 10^5
Time Limit: 1 sec
CodingNinjas
author
2y
Sub-Optimal Approach
Approach :
- We first notice that the pairs (‘n1’,’s1’) and (‘n2’,’s2’) will cross each other if either :
- ‘n1’ < ‘n2’ and ‘s1’ > ‘s2’
- ‘n1’ > ‘n2’ and ‘s1’ < ‘s2’
- To reduce the cases, ...read more
CodingNinjas
author
2y
Optimal Approach
Approach :
- In the previous approach, we were finding the longest increasing subsequence among the south coordinates in O(N^2).
- Here, we will find the longest increasing subsequence in...read more
Help your peers!
Add answer anonymously...
Top Newgen Software Technologies Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Top HR questions asked in Newgen Software Technologies Software Engineer
>
Newgen Software Technologies Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app