# Find the largest interval that contains exactly one of the given N integers In C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have an array of N distinct integers. We have to find the max element in an interval [L, R] such that the interval contains exactly one of the given N integers and 1 <= L <= R <= 105.

So if the array is like Arr = [5, 10, 200], then output is 99990. So all possible intervals are [1, 9], [6, 199] and [11, 100000]. The last one has the maximum integers like 99990

The idea is simple. We will fix the element that we want our interval to contain. Now, we will see how we can extend our interval to left and right without overlapping other elements. So we have to sort the array first, then for a fixed element, we determine the end using previous and next element. We will take care of the corner cases. So when we are fixing the first and last intervals. This way for every element i, we find the maximum length of the interval.

## Example

Live Demo

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int maximumSize(vector<int>& vec, int n) {
vec.push_back(0);
vec.push_back(100001);
n += 2;
sort(vec.begin(), vec.end());
int max_value = 0;
for (int i = 1; i < n - 1; i++) {
int Left = vec[i - 1] + 1;
int Right = vec[i + 1] - 1;
int count = Right - Left + 1;
max_value = max(max_value, count);
}
return max_value;
}
int main() {
vector<int> v;
v.push_back(200);
v.push_back(10);
v.push_back(5);
int n = v.size();
cout << "Maximum Size is: " << maximumSize(v, n);
}

## Output

Maximum Size is: 99990
Updated on 18-Dec-2019 11:35:57