Amazon Interview Question

Find an alternative way to optimize the algorithm.