HackerRank C++ Attending Workshops




A student signed up for n workshops and wants to attend the maximum number of workshops where no two workshops overlap. You must do the following:

Implement 2 structures:

struct Workshop having the following members:

The workshop's start time.
The workshop's duration.
The workshop's end time.
struct Available_Workshops having the following members:

An integer, n (the number of workshops the student signed up for).
An array of type Workshop array having size n.



  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. //Define the structs Workshops and Available_Workshops.
  4. //Implement the functions initialize and CalculateMaxWorkshops
  5. struct Workshops {
  6. int start_time;
  7. int duration;
  8. int end_time;
  9. };
  10. struct Available_Workshops {
  11. int n;
  12. vector <Workshops> w;
  13. };
  14. Available_Workshops *initialize(int *start_time, int *duration, int n) {
  15. Available_Workshops *paw=new(Available_Workshops);
  16. Workshops ws;
  17. paw->n=n;
  18. for (int i=0;i<n;i++) {
  19. //construct a Workshops
  20. ws.start_time=start_time[i];
  21. ws.duration=duration[i];
  22. ws.end_time=start_time[i]+duration[i];
  23. paw->w.push_back(ws);
  24. }
  25. return paw;
  26. }
  27. bool compare(Workshops w1, Workshops w2) {
  28. return (w1.end_time < w2.end_time);
  29. }
  30. int CalculateMaxWorkshops(Available_Workshops* ptr) {
  31. // sort workshops by end_time
  32. sort(ptr->w.begin(),ptr->w.end(),compare);
  33. // interval scheduling
  34. int last_processed_time=-1;
  35. int maxWorkshops=0;
  36. for (int i=0;in;i++) {
  37. if (ptr->w[i].start_time >= last_processed_time) {
  38. last_processed_time=ptr->w[i].end_time;
  39. maxWorkshops++;
  40. }
  41. }
  42. return maxWorkshops;
  43. }
  44. int main(int argc, char *argv[]) {
  45. int n; // number of workshops
  46. cin >> n;
  47. // create arrays of unknown size n
  48. int* start_time = new int[n];
  49. int* duration = new int[n];
  50. for(int i=0; i < n; i++){
  51. cin >> start_time[i];
  52. }
  53. for(int i = 0; i < n; i++){
  54. cin >> duration[i];
  55. }
  56. Available_Workshops * ptr;
  57. ptr = initialize(start_time,duration, n);
  58. cout << CalculateMaxWorkshops(ptr) << endl;
  59. return 0;
  60. }




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube