improved solution using dynamic programming