Amazon interview question

Find an alternative way to optimize the algorithm.