Snippets

Camilo Rocha Activity scheduling algorithm (greedy approach)

Created by Camilo Rocha last modified
def act_sch(a):
  # Pre: a[0..N) is a list of activities (s,f), where s denotes the
  # start time of an activity and f its finishing time (s<=f)
  # Post: maximum number of compatible activities in a[0..N)
  a.sort(key=lambda x : x[1])  # sort activities by earliest finish time
  ans,n,N = 0,0,len(a)
  while n!=N:
    best,n,ans = n,n+1,ans+1
    while n!=N and a[n][0]<a[best][1]:
      n += 1
  return ans

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.