Amazon interview question

Leet code question similar to course schedule II.