The way you are using erase
is causing the problem in this case. In fact, you exactly don't need a complex approach like this for the problem.
You can simply sort the array in reverse order and then use pop_back()
while last element is 0
. It will also help to reduce complexity as then you won't need to call min_element
each time. You can directly use arr.back()
for the minimum element.
Logic behind my approach:
In each iteration, you are subtracting minimum element from each element. This makes number(s) having the minimum value as 0
. Clearly, since the array is sorted in reverse order, these numbers will be in the end of the array. You then want to remove these elements for which pop_back
is one of the best available options.
Here is sample code:
vector<int> cutTheSticks(vector<int> arr) {
vector<int> res;
sort(arr.begin(), arr.end(), greater<int>());
while (not arr.empty()) {
res.push_back(arr.size());
for (auto &&i : arr)
i -= arr.back();
while (not (arr.back() or arr.empty()))
arr.pop_back();
}
return res;
}
PS:
If you want to stick with your original algorithm then replace
for (auto it = arr.begin(); it!=arr.end(); it++) {
i = *it;
if(i == 0)
arr.erase(it);
}
with something like:
arr.erase(remove(arr.begin(), arr.end(), 0), arr.end()); // called as erase-remove idiom
or
for (auto it = arr.begin(); it!=arr.end(); /* it++ */) {
i = *it;
if(i == 0)
it = arr.erase(it);
else
++it;
}
This thread may help you: Remove elements of a vector inside the loop.