Amazon Interview Question

Is there a more optimal way to perform this?