This is a generic dynamic programming algorithm framework.