Pergunta de entrevista da empresa Nabla

How can we optimize the space-time complexity of this algorithm?