A dynamic programming solution to an interview question I felt like hacking up