Amazon interview question

It was from array but need to optimize.