Calculate next in chain
Faster solution with dynamic programming