Provided an N horizontal line sectors are set up on the X-axis of a 2D aircraft. The start and end point of each line sector is given up an Nx2 matrix lines[ ][ ], the job is to discover the optimal number of crossways possible of any vertical line with the offered N line sectors.
Examples:
Input: N = 4, lines[][] = {{1, 3}, {2, 3}, {1, 2}, {4, 4}}
Output: 3
Description: A vertical line at X = 2 goes through {1, 3}, {2, 3}, {1, 2}, ie 3 of the offered horizontal lines.Input: N = 3, lines[][] = {{1, 3}, {5, 6}, {3, 4}}
Output: 2
Description: A vertical line at X = 3 goes through 2 of the offered horizontal lines which are the optimum possible.
Technique: This can be resolved with the following concept:
Utilizing hashMap, we can identify the optimum worth amongst all the points and return it as a response.
Follow the actions pointed out listed below to execute the concept:
- Take the n, the variety of horizontal lines, and matrix lines[][]
- Produce a map to keep the variety of lines at each x-coordinate.
- Repeat through each line and upgrade the map appropriately.
- Initialize variables to track the optimum variety of crossways and an amount to track the variety of lines at each x-coordinate
- Repeat through the map and upgrade the amount and optimum appropriately.
- Return the optimum variety of crossways.
Below is the application of the above method:
C++
// C++ code for the above method: . #include < bits/stdc++. h> > . utilizing namespace sexually transmitted disease; . .// Function to discover optimal crossways . int maxIntersections( vector<< vector < int > > lines, int N) . { . .// Produce a map to keep the number .// of lines at each x-coordinate <. map < int>, int > mp; . .// Repeat through each line and .// upgrade the map appropriately . for (int i < =0; i < lines.size(); i++) { . int a= lines[i][0]; . int b =lines[i][1]; . mp[a]++; . mp[b + 1]--; . } . .// Initialize with minimum worth . // of integer . int res= INT_MIN; . int amount= 0; . .// Repeat through the map and upgrade . // the amount and optimum appropriately . for( automobile it: mp) { . amount += it.second; . res= max( res, amount); . } . . // Return the optimum number . // of crossways . return res; .} . ./ >/ Motorist code . int primary( ) . { . . int n = 4; . vector < vector < int > > mat . = {{1, 3}, {2 , 3 } , {1, << 2}, {4 <<, 4}}; . .// Function call . cout < < maxIntersections( mat, n) < < endl; .}
Time Intricacy: O( N * log( N))
Auxiliary Area: O (N)
.