Attending Workshops

  • + 0 comments
    struct Workshop {
        int start_time;
        int duration;
        int end_time;
    };
    
    struct Available_Workshops {
        int n {0};
        Workshop* workshops;
        
        Available_Workshops(int n) : n(n) {
            workshops = new Workshop[n];
        }
        ~Available_Workshops() {
            delete[] workshops;
            workshops = nullptr;
        }
    };
    
    Available_Workshops* initialize(int *start_time, int *duration, int n) {
        Available_Workshops* obj = new Available_Workshops(n); 
        for (int i = 0; i < n; ++i) {
            obj->workshops[i].start_time = start_time[i];
            obj->workshops[i].duration = duration[i];
            obj->workshops[i].end_time = start_time[i] + duration[i];
        }
        return obj;
    }
    
    int CalculateMaxWorkshops(Available_Workshops *ptr) {
        if (ptr == nullptr || ptr->workshops == nullptr || ptr->n <= 0)
            return 0;
    
        // Sort workshops based on their END times
        std::sort(ptr->workshops, ptr->workshops + ptr->n, 
            [](const Workshop& a, const Workshop& b) {
                return a.end_time < b.end_time;
            }
        );
    
        int maxWorkshops {0}, endTime {0};
        for (int i {0}; i < ptr->n; ++i) {
            if (ptr->workshops[i].start_time >= endTime) {
                // Non-overlapping workshop found
                ++maxWorkshops;
                endTime = ptr->workshops[i].end_time;
            }
        }
        return maxWorkshops;
    };