Dynamic programming solution for problem B