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

C++Server Side ProgrammingProgramming

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.


 Live Demo

using namespace std;
int maximumSize(vector<int>& vec, int n) {
   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;
   int n = v.size();
   cout << "Maximum Size is: " << maximumSize(v, n);


Maximum Size is: 99990
Published on 18-Dec-2019 11:34:50