Improve recursive algorithm for problem 18