Amazon interview question

optimized solution need to be derived