My code shows time limit error! What could be a more efficient way?

u will have to use dyanmic programming