Challenge - 5 Problems
Activity Selection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Greedy Activity Selection
What is the output of the following code that selects the maximum number of non-overlapping activities?
DSA Python
def activity_selection(start, finish): n = len(start) selected = [0] last_finish = finish[0] for i in range(1, n): if start[i] >= last_finish: selected.append(i) last_finish = finish[i] return selected start = [1, 3, 0, 5, 8, 5] finish = [2, 4, 6, 7, 9, 9] print(activity_selection(start, finish))
Attempts:
2 left
💡 Hint
Look for activities that start after or exactly when the last selected activity finishes.
✗ Incorrect
The code selects activities greedily by earliest finish time. It starts with activity 0, then picks activity 1 (start 3 >= finish 2), then activity 3 (start 5 >= finish 4), then activity 4 (start 8 >= finish 7).
🧠 Conceptual
intermediateKey Idea Behind Activity Selection
What is the main idea behind the greedy approach to solve the Activity Selection Problem?
Attempts:
2 left
💡 Hint
Think about which choice leaves the most room for other activities.
✗ Incorrect
Choosing the activity that finishes earliest allows more time for the remaining activities, maximizing the total number selected.
🔧 Debug
advancedIdentify the Bug in Activity Selection Code
What error does the following code produce when run, and why?
```python
def activity_selection(start, finish):
n = len(start)
selected = []
last_finish = 0
for i in range(n):
if start[i] >= last_finish:
selected.append(i)
last_finish = finish[i]
return selected
start = [1, 3, 0, 5, 8, 5]
finish = [2, 4, 6, 7, 9, 9]
print(activity_selection(start, finish))
```
Attempts:
2 left
💡 Hint
Check if the activities are sorted by finish time before selection.
✗ Incorrect
The code does not sort activities by finish time, so it picks activities in input order, leading to a suboptimal and incorrect selection.
🚀 Application
advancedMaximum Activities Count
Given the start and finish times below, what is the maximum number of activities that can be selected without overlap?
start = [4, 1, 3, 0, 5, 8, 5]
finish = [5, 2, 4, 6, 7, 9, 9]
Attempts:
2 left
💡 Hint
Sort activities by finish time and count how many can fit without overlapping.
✗ Incorrect
After sorting by finish times: activities with finish times 2,4,5,6,7,9,9. Selecting activities 1,2,0,4,5 gives 5 activities without overlap.
🧠 Conceptual
expertWhy Greedy Works for Activity Selection
Why does the greedy algorithm that selects the earliest finishing activity always produce an optimal solution for the Activity Selection Problem?
Attempts:
2 left
💡 Hint
Think about how the choice affects the remaining activities.
✗ Incorrect
Choosing the earliest finishing activity frees up the timeline for more activities to fit, which is why the greedy approach is optimal.
