forked from Annex5061/java-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ActivitySelection.java
51 lines (42 loc) · 1.62 KB
/
ActivitySelection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.util.ArrayList;
import java.util.Collections;
public class ActivitySelection {
static class Activity {
int start;
int end;
public Activity(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public String toString(){
return "[" + this.start + ", " + this.end + "]";
}
}
public static void maxActivities(ArrayList<Activity> activities){
//sort the activities in ascending order of meeting finish time
System.out.println("Given Activities: " + activities);
Collections.sort(activities, (o1, o2) -> o1.end - o2.end);
ArrayList<Activity> selectedActivities = new ArrayList<>();
int currentEnd = -1;
for (int i = 0; i <activities.size() ; i++) {
Activity currentActivity = activities.get(i);
if(currentActivity.start >currentEnd){
selectedActivities.add(currentActivity);
currentEnd = currentActivity.end;
}
}
//print selected activities
System.out.println("Selected Activities: " + selectedActivities);
}
public static void main(String[] args) {
ArrayList<Activity> activities = new ArrayList<>();
activities.add(new Activity(1, 3));
activities.add(new Activity(2, 5));
activities.add(new Activity(0, 7));
activities.add(new Activity(6, 8));
activities.add(new Activity(9, 11));
activities.add(new Activity(10, 12));
maxActivities(activities);
}
}