Amazon Interview Question

graphs question.time complexity of the approach,optimal solution