Pergunta de entrevista da empresa Meta

Solve this algorithm problem in an optimised way