Amazon interview question

Algorithm optimization question.