0

I tried to get first a greedy solution for me handling reservation buy getting 2 days (start, end) and getting the maximum days that can be reserved without the interval being overlap

#include <algorithm>
#include <iostream>
using namespace std;



struct Interval {

    int start, end;
};

// Compares two intervals
// according to starting times.

bool comparesorting(Interval i1, Interval i2)//sorting
{

    return (i1.end < i2.end);
}

bool compareoverlap(Interval i1, Interval i2)//overlap
{
    return (i1.start < i2.start) ? true : false;
}


bool isIntersect(Interval arr[], int n)
{
    // Sort intervals in increasing order of start time
    sort(arr, arr + n, compareoverlap);

    // In the sorted array, if start time of an interval
    // is less than end of previous interval, then there
    // is an overlap
    for (int i = 1; i < n; i++)
        if (arr[i - 1].end > arr[i].start)
            //return true;
    if (true) {
        
            for (int i = 0; i < n; i++)
                cout << "mmmm" << endl;
            cout << "[" << arr[i].start << "," << arr[i].end

                << "] ";
        

    }
    




    // If we reach here, then no overlap
    return false;
    



  
}
int main()
{

    Interval arr[] 

       = { { 6, 8 }, { 7, 9 }, { 2, 4 }, { 4, 7 } , { 1,9 } , {6,9} ,{2,6} , {1,10} };
       


    int n = sizeof(arr) / sizeof(arr[0]);


    // sort the intervals in increasing order of

    // start time

    sort(arr, arr + n, comparesorting);


    cout << "Intervals sorted  : \n";

    for (int i = 0; i < n; i++)

        cout << "[" << arr[i].start << "," << arr[i].end

        << "] ";

 int n1 = sizeof(arr) / sizeof(arr[0]);
    isIntersect(arr, n1) ? cout << "Yes\n" : cout << "No\n";

return 0;
}

the output should be {2,4} {4,7} (that does not overlap)

I'm trying to make an optimal solution to solve this problem. I'm thinking to subtract the end - start and compare it to the addition of this greedy solution please help I'm stuck!!!!

joergbrech
  • 2,056
  • 1
  • 5
  • 17
kobi
  • 9
  • 1
  • I don't quite understand your question. What are the inputs and the outputs exactly? From your question it is not clear that you have several intervals. Which subinterval do you want to maximize? Why are you expecting `{2,4} {4,7}` to be the output? I tried to understand your question by reading your code, but this needs some serious cleanup as well: `isIntersect` always returns false and you don't actually calculate anything. You just sort an array of `Interval` and print stuff to the console. So please: Rephrase your question and thoroughly cleanup your minimal code example. – joergbrech Dec 11 '22 at 21:38

0 Answers0