Refactored logic and added logic for maxValueFromWeight