Nabla interview question

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