Snippets

Camilo Rocha Activity scheduling algorithm (greedy approach)

Updated by Camilo Rocha

File act_sch.py Modified

  • Ignore whitespace
  • Hide word diff
 def act_sch(a):
   # Pre: a[0..N) is a list of activities (s,f), where s denotes the
-  # start time of a and f its finish time (s<=f)
+  # 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)
Updated by Camilo Rocha

File act_sch.py Modified

  • Ignore whitespace
  • Hide word diff
 def act_sch(a):
-  # Pre: a[0..N) is a list of activities a=(s,f), where s denotes the
+  # Pre: a[0..N) is a list of activities (s,f), where s denotes the
   # start time of a and f its finish 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
Created by Former user

File act_sch.py Added

  • Ignore whitespace
  • Hide word diff
+def act_sch(a):
+  # Pre: a[0..N) is a list of activities a=(s,f), where s denotes the
+  # start time of a and f its finish 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
HTTPS SSH

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