Caching intermediate results, fixed checking if last item has bigger weight than total. Tests passed.