Second implementation, DP. Improved space complexity