Amazon interview question

Question based on recursion, but there is also non recursive way to solve the problem