DP based solution, linear