Skip to content

Commit e5f4d5f

Browse files
committed
💥 Activity Selection Problem added
1 parent e138bc4 commit e5f4d5f

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Activity implements Comparable<Activity> {
2+
3+
Integer startTime = 0;
4+
Integer finishTime = 0;
5+
6+
Activity(Integer st, Integer ft) {
7+
startTime = st;
8+
finishTime = ft;
9+
}
10+
11+
@Override
12+
public int compareTo(Activity activity) {
13+
return this.finishTime.compareTo(activity.finishTime);
14+
}
15+
16+
@Override
17+
public String toString() {
18+
return "(" + startTime + "," + finishTime + "), ";
19+
}
20+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* You are given n activities with their start and finish times.
3+
* Select the maximum number of activities that can be performed by a single person,
4+
* assuming that a person can only work on a single activity at a time.
5+
*
6+
* TIME COMPLEXITY :
7+
* O(n log n) time if input activities may not be sorted.
8+
* O(n) time when it is given that input activities are always sorted.
9+
*
10+
*/
11+
12+
13+
import java.util.ArrayList;
14+
import java.util.Collections;
15+
import java.util.Random;
16+
17+
public class ActivitySelectionProblem {
18+
19+
public static void selectActivities() {
20+
21+
ArrayList<Activity> activities = new ArrayList<Activity>();
22+
23+
activities.add(new Activity(5,9));
24+
activities.add(new Activity(1,2));
25+
activities.add(new Activity(3,4));
26+
activities.add(new Activity(0,6));
27+
activities.add(new Activity(5,7));
28+
activities.add(new Activity(8,9));
29+
30+
Collections.sort(activities);
31+
32+
int st = -1;
33+
34+
35+
System.out.print("\nSelected Activities are: [");
36+
for (int i = 0; i < activities.size(); i++) {
37+
if (activities.get(i).startTime >= st) {
38+
System.out.print(activities.get(i));
39+
st = activities.get(i).finishTime;
40+
}
41+
}
42+
System.out.println("]\n");
43+
}
44+
45+
public static void main(String[] args){
46+
selectActivities();
47+
}
48+
}

0 commit comments

Comments
 (0)