Amazon Interview Question

optimized solution need to be derived