Nabla Interview Question

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