refactored algorithm to be more efficient, note that we might need quantity data