Hint: Count activities starting after last selected finish time [OK]
Common Mistakes:
Not sorting activities by finish time
Selecting overlapping activities
Incorrectly updating last_finish
4. Identify the error in the following C code snippet for the Activity Selection Problem:
typedef struct {
int start;
int finish;
} Activity;
Activity activities[] = {{1, 3}, {2, 5}, {4, 7}};
int n = 3;
// Activities are sorted by finish time
int count = 0;
int last_finish = 0;
for (int i = 0; i < n; i++) {
if (activities[i].start > last_finish) {
count++;
last_finish = activities[i].finish;
}
}
printf("%d\n", count);
medium
A. The condition should be activities[i].start >= last_finish
B. The loop should start from i = 1, not 0
C. last_finish should be initialized to activities[0].finish
D. The activities array is not sorted
Solution
Step 1: Analyze the selection condition
The condition uses '>' which excludes activities starting exactly at last_finish time. It should allow activities starting at or after last_finish, so '>=' is correct.
Step 2: Check other parts
Starting loop at 0 and initializing last_finish to 0 is fine if condition is corrected. The activities are sorted as stated.
Final Answer:
The condition should be activities[i].start >= last_finish -> Option A
Quick Check:
Use >= to include activities starting at last finish [OK]
Hint: Use >= to allow activities starting exactly at last finish [OK]
Common Mistakes:
Using > excludes valid activities
Starting loop from 1 unnecessarily
Wrong initialization of last_finish
5. Given the following activities with start and finish times: