boxstack solution using dynamic programming