dynamic programming implementation to find optimal cut with given patterns