Try dynamic programming