interesting problem. Be clear of pointers.
classic DP problem.