# Maximum ranges that can be uniquely represented by any integer from the range

Given an array arr[] consisting of N ranges of the form {L, R}, the task is to find the maximize the number of ranges such that each range can be uniquely represented by any integer from that range.Examples:Input: arr[] = {{1, 2}, {2, 3}, {3, 4}}Output: 3Explanation:Number of ranges can be maximized by following representations:Range {1, 2} can be represented by 1.Range {2, 3} can be represented by 2.Range {3, 4} can be represented by 3.Therefore, the maximized count of ranges is 3.Input: arr[] = {{1, 4}, {4, 4}, {2, 2}, {3, 4}, {1, 1}}Output: 4Naive Approach: The simplest approach to solve the given problem is to sort the ranges and iterate from the minimum value of L to the maximum value of R to greedily assign an integer for a particular range and keep a count of the possible assigned integers. After completing the above steps, print the count obtained as the result.Time Complexity: O(M * N), where M is the maximum element among the given ranges.Auxiliary Space: O(1)Efficient Approach: The above approach can also be optimized by using the Greedy Approach, the idea is to assign the minimum unique value from each range by selecting the given ranges in increasing order. Follow the steps to solve the problem:Sort the given array of ranges in ascending order.Initialize a vector, say prev as arr[] that stores the previously assigned values to the given ranges.Initialize a variable, say count as 1 to store the maximum number of ranges where each range can be uniquely represented by an integer from the range.Traverse the given array arr[] over the range [1, N – 1] and perform the following steps:Initialize a vector, say current[] as arr[i] that stores the values assigned to the current range.If the value of max(current[i][1], prev[i][1]) – max(current[i][0], prev[i][0] – 1) is positive, then update the value of prev as {1 + max(current[i][0], prev[i][0] – 1), max(current[i][1], prev[i][1])} and increment the value of count by 1.Otherwise, check of the next range.After completing the above steps, print the value of count as the result.Below is the implementation of the above approach:C++ #include using namespace std; int maxRanges(vector arr, int N){ sort(arr.begin(), arr.end()); int count = 1; vector prev = arr[0]; for (int i = 1; i < N; i++) { vector last = arr[i - 1]; vector current = arr[i]; if (last[0] == current[0] && last[1] == current[1] && current[1] == current[0]) continue; int start = max(prev[0], current[0] - 1); int end = max(prev[1], current[1]); if (end - start > 0) { prev[0] = 1 + start; prev[1] = end; count++; } } return count;} int main(){ vector range = { { 1, 4 }, { 4, 4 }, { 2, 2 }, { 3, 4 }, { 1, 1 } }; int N = range.size(); cout