Amazon interview question

graphs question.time complexity of the approach,optimal solution