Amazon Interview Question

It was from array but need to optimize.