You end up computing problem.quality(n) twice here, which isn't super efficient.