Activity Selection Problem in Java

This Java snippet defines a class for activities and a method to solve the activity selection problem by sorting and selecting non-overlapping activities based on their finishing times.
 avatar
unknown
java
a year ago
1.1 kB
6
Indexable
import java.util.*;


class Activity {

    int startingTime, finishingTime;

    public Activity(int startingTime, int finishingTime) {

        this.startingTime = startingTime;
        this.finishingTime = finishingTime;

    }
}

public class Solution
{
    public static int activitySelection(int start[], int end[], int n)
    {
         Activity activities[] = new Activity[start.length];

        for (int i = 0; i < activities.length; i++) {
            activities[i] = new Activity(start[i], end[i]);
        }

        Arrays.sort(activities, (o1, o2) -> {

            return o1.finishingTime - o2.finishingTime;
        });

        int count = 1;
        int currFinishingTime = activities[0].finishingTime;

        for (int i = 1; i < activities.length; i++) {
            if (activities[i].startingTime >= currFinishingTime) {
                count++;
                currFinishingTime = activities[i].finishingTime;
            }
        }

        return count;




      
        
    }
}
Editor is loading...
Leave a Comment