DP algorithm works