Activity Selection (Interval Scheduling) in Java: Explanation & Practice

Select maximum non-overlapping activities

Problem summary

Given n activities with start and end times, select the maximum number of activities that can be performed by a single person (no overlapping).

Starter code

public class Main {
    public static void main(String[] args) {
        int[] start = {1, 3, 0, 5, 8, 5};
        int[] end = {2, 4, 6, 7, 9, 9};
        
        // Greedy: always pick activity that ends earliest
        // Sort by end time
        // Select if start >= last selected end
        // Print: Max activities: 4
    }
}

Expected output and test cases

  • Select 4 non-overlapping
    Max activities: 4
  • Only 2 possible
    Max activities: 2
  • All overlap → pick 1
    Max activities: 1

Hints

  1. Sort activities by end time
  2. Always pick the activity that finishes earliest
  3. This leaves maximum room for remaining activities
  4. After picking, skip all overlapping activities

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler