Maximum points covered after removing an Interval in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find maximum points covered after removing an Interval

For this we will be provided with N intervals and the maximum range value . Our task is to find that one interval which when removed will give us the maxim numbers in the given range from 1 to maximum range value

Example

 Live Demo

#include <bits/stdc++.h>
#define ll long long int
using namespace std;
//finding required interval
void solve(int interval[][2], int N, int Q) {
   int Mark[Q] = { 0 };
   for (int i = 0; i < N; i++) {
      int l = interval[i][0] - 1;
      int r = interval[i][1] - 1;
      for (int j = l; j <= r; j++)
         Mark[j]++;
   }
   //counting covered numbers
   int count = 0;
   for (int i = 0; i < Q; i++) {
      if (Mark[i])
         count++;
   }
   int count1[Q] = { 0 };
   if (Mark[0] == 1)
      count1[0] = 1;
   for (int i = 1; i < Q; i++) {
      if (Mark[i] == 1)
         count1[i] = count1[i - 1] + 1;
      else
         count1[i] = count1[i - 1];
   }
   int maxindex;
   int maxcoverage = 0;
   for (int i = 0; i < N; i++) {
      int l = interval[i][0] - 1;
      int r = interval[i][1] - 1;
      int elem1;
      if (l != 0)
         elem1 = count1[r] - count1[l - 1];
      else
         elem1 = count1[r];
      if (count - elem1 >= maxcoverage) {
         maxcoverage = count - elem1;
         maxindex = i;
      }
   }
   cout << "Maximum Coverage is " << maxcoverage << " after removing interval at index " << maxindex;
}
int main() {
   int interval[][2] = {
      { 1, 4 },
      { 4, 5 },
      { 5, 6 },
      { 6, 7 },
      { 3, 5 }
   };
   int N = sizeof(interval) / sizeof(interval[0]);
   int Q = 7;
   solve(interval, N, Q);
   return 0;
}

Output

Maximum Coverage is 7 after removing interval at index 4
raja
Published on 09-Sep-2020 12:08:40
Advertisements