Code to find conflicts in a list of meetings given as input. Meetings are defined as {startTime, endTime}. I am using a Greedy Algorithm to find the conflicts. Wanted to know if there is a more efficient way of solving this problem.
Example:
Input: `meetings[] = { {1, 5} {3, 7}, {2, 6}, {10, 15}, {5, 6}, {4, 100}}`
Output: Number of Conflicts : 4
The code:
// Meeting Class
class Meeting implements Comparable<Meeting> {
int startTime;
int endTime;
public Meeting(int startTime, int endTime) {
super();
this.startTime = startTime;
this.endTime = endTime;
}
@Override
public int compareTo(Meeting o) {
if(this.startTime == o.startTime) return 0;
if(this.startTime < o.startTime) return -1;
return 1;
}
}
Class which computes the conflicts
public class FindConflictingMeetingsProblem {
// static function to find conflicts
public static int findNumberOfConflicts(List<Meeting> meetings){
// sort the meetings in ascending order of start time
Collections.sort(meetings,new Comparator<Meeting>(){
@Override
public int compare(Meeting o1, Meeting o2) {
return o1.compareTo(o2);
}
});
int conflicts = 0;
// count the conflicts
for(int i = 0 ; i < meetings.size();i++){
if(i > 1 && meetings.get(i-1).endTime > meetings.get(i).startTime){
conflicts++;
}
}
return conflicts;
}
public static void main(String[] args) {
Meeting m1 = new Meeting(1, 2);
Meeting m2 = new Meeting(2, 5);
Meeting m4 = new Meeting(4, 5);
Meeting m5 = new Meeting(7, 8);
List<Meeting> meetingsList = new ArrayList<Meeting>();
meetingsList.add(m1);
meetingsList.add(m2);
meetingsList.add(m4);
meetingsList.add(m5);
System.out.println(" Number of conflicts :"+findNumberOfConflicts(meetingsList));
}
}