Dynamic programming solution to problem 18