-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathIntervalSchedulingSolver.cs
More file actions
42 lines (37 loc) · 1.17 KB
/
IntervalSchedulingSolver.cs
File metadata and controls
42 lines (37 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Problems.JobScheduling;
/// <summary>
/// Implements the greedy algorithm for Interval Scheduling.
/// Finds the maximum set of non-overlapping jobs.
/// </summary>
public static class IntervalSchedulingSolver
{
/// <summary>
/// Returns the maximal set of non-overlapping jobs.
/// </summary>
/// <param name="jobs">List of jobs to schedule.</param>
/// <returns>List of selected jobs (maximal set).</returns>
public static List<Job> Schedule(IEnumerable<Job> jobs)
{
if (jobs == null)
{
throw new ArgumentNullException(nameof(jobs));
}
// Sort jobs by their end time (earliest finish first)
var sortedJobs = jobs.OrderBy(j => j.End).ToList();
var result = new List<Job>();
int lastEnd = int.MinValue;
foreach (var job in sortedJobs)
{
// If the job starts after the last selected job ends, select it
if (job.Start >= lastEnd)
{
result.Add(job);
lastEnd = job.End;
}
}
return result;
}
}