Pregunta de entrevista de Nabla

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