Algorithm for the closest candy + refactoring