Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to sort activities by their finish time.
DSA Java
Arrays.sort(activities, (a, b) -> a.[1] - b.finish);Attempts:
3 left
💡 Hint
Common Mistakes
Sorting by start time instead of finish time.
Using wrong field names.
✗ Incorrect
We sort activities by their finish time to select the maximum number of non-overlapping activities.
2fill in blank
mediumComplete the code to select the first activity after sorting.
DSA Java
int count = 1; int lastFinish = activities[0].[1];
Attempts:
3 left
💡 Hint
Common Mistakes
Using start time instead of finish time.
Not initializing count to 1.
✗ Incorrect
We select the first activity and store its finish time to compare with next activities.
3fill in blank
hardFix the error in the condition to select the next compatible activity.
DSA Java
for (int i = 1; i < activities.length; i++) { if (activities[i].[1] >= lastFinish) { count++; lastFinish = activities[i].finish; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing finish time instead of start time.
Using wrong comparison operator.
✗ Incorrect
We check if the start time of the current activity is after or equal to the last selected activity's finish time.
4fill in blank
hardFill both blanks to create a method that returns the maximum number of activities.
DSA Java
public static int maxActivities(Activity[] activities) {
Arrays.sort(activities, (a, b) -> a.[1] - b.[2]);
int count = 1;
int lastFinish = activities[0].finish;
for (int i = 1; i < activities.length; i++) {
if (activities[i].start >= lastFinish) {
count++;
lastFinish = activities[i].finish;
}
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different fields for sorting.
Sorting by start time instead of finish time.
✗ Incorrect
Both blanks must be 'finish' to sort activities by their finish time.
5fill in blank
hardFill all three blanks to create a loop that counts compatible activities.
DSA Java
int count = 1; int lastFinish = activities[0].finish; for (int i = [1]; i < activities.length; i[2]) { if (activities[i].[3] >= lastFinish) { count++; lastFinish = activities[i].finish; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting loop at 0 instead of 1.
Using wrong increment operator.
Comparing finish time instead of start time.
✗ Incorrect
Start loop at 1, increment i by ++, and compare start time with lastFinish.
