-1

I'm trying to solve the Activity Selection problem using the greedy algorithm. My code fails for some inputs. I'm sorting the activity list based on the finish_time_list.

The code works fails for the following input:

activity_list=[1, 2, 3, 4, 5, 6]

start_time_list=[5, 4, 8, 2, 3, 1]

finish_time_list=[13, 6, 16, 7, 5, 4]

My sorted activity list: [6, 5, 2, 4, 1, 3]

def find_maximum_activities(activity_list,start_time_list, finish_time_list):

    selected =[]


    activity_tmp_list = [x for _,x in sorted(zip(finish_time_list,activity_list))]

    #the first activity is always selected
    i=0
    #print(i)
    selected.append(activity_tmp_list[i])

    #consider rest of Activities
    for j in range(1,len(activity_list)):

        if start_time_list[j]>=finish_time_list[i]:
            print(j)
            selected.append(activity_tmp_list[j])
            i=j
    return selected

activity_list=[1, 2, 3, 4, 5, 6]
start_time_list=[5, 4, 8, 2, 3, 1]
finish_time_list=[13, 6, 16, 7, 5, 4]

print("Activities:",activity_list)
print("Start time of the activities:",start_time_list)
print("Finishing time of the activities:", finish_time_list)

result=find_maximum_activities(activity_list,start_time_list, finish_time_list)
print("The maximum set of activities that can be completed:",result)

Expected Output: [6,1]

Actual Result: [6]

HackersInside
  • 307
  • 2
  • 6
  • 17

1 Answers1

1

The issue is that in your for loop, you're comparing each start time to finish_time_list[i]. i=0 every time the loop runs, and in this case, finish_time_list[0] is 13, which is the last to end, so that if will never become true.

Another issue is that you're checking as j goes through start_time_list, but you append with that same j from activity_tmp_list, which has been sorted. Because it's been sorted, the activity indices won't line up like you want.

The more higher-level issue is that you're only storing the activity number in the selected array, nothing about when it starts or ends. Without knowing that information about what has already been selected, you can't decide whether or not add another activity. I would recommend either making an Activity class containing its label, start time, and end time, or making selected a 2D matrix, so that after it selects the first activity, it looks something like [[6, 1, 4]], containing the label, where it starts, and where it ends. Or minimally, just the label and the end time, assuming you want to keep the greedy algorithm.

If you have any other questions, let me know.

Calvin Godfrey
  • 2,171
  • 1
  • 11
  • 27