Longest Interval Containing One Number in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of distinct integers called nums. We have to find the size of the largest interval (inclusive) [start, end] such that it contains at most one number in nums.

So, if the input is like nums = [10, 6, 20], then the output will be 99990, as the largest interval is [11, 100000], this contains 20 only.

To solve this, we will follow these steps −

  • ret := -inf

  • end := 100000

  • prev := 1

  • sort the array nums

  • n := size of nums

  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −

    • if i + 1 < n, then −

      • high := nums[i + 1] - 1

    • Otherwise

      • high := end

    • if i - 1 >= 0, then −

      • low := prev + 1

    • Otherwise

      • low := prev

    • prev := nums[i]

    • ret := maximum of high - low + 1 and ret

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int solve(vector<int> &nums) {
      int ret = INT_MIN;
      int end = 100000;
      int prev = 1;
      sort(nums.begin(), nums.end());
      int n = nums.size();
      int low, high;
      for (int i = 0; i < nums.size(); i++) {
         if (i + 1 < n) {
            high = nums[i + 1] - 1;
         } else
         high = end;
         if (i - 1 >= 0) {
            low = prev + 1;
         } else
         low = prev;
         prev = nums[i];
         ret = max(high - low + 1, ret);
      }
      return ret;
   }
};
main() {
   Solution ob;
   vector<int> v = {10, 6, 20};
   cout << (ob.solve(v));
}

Input

{10, 6, 20}

Output

99990
raja
Published on 02-Sep-2020 11:24:40
Advertisements