I’m experiencing a strange issue with two similar pieces of C++ code that are supposed to perform the same task but yield different results.
The problem is around the inner loop statement .
I was trying to solve QUESTION.
While implementing the solution,I came across this issue:-
int n;
cin >> n;
vector<int> arr(n);
REP(i, 0, n){
cin >> arr[i];
}
vector<int> dup = arr;
int maxVal = INT_MIN;
REP(i, 0, n){
if (arr[i] > maxVal){
maxVal = arr[i];
}
if (arr[i] < maxVal){
arr[i] = maxVal;
}
}
REP(i, 0, n){
dup[i] = arr[i] - dup[i];
}
int ans = 0;
sort(dup.begin(), dup.end());
REP(i, 0, n){
if (dup[i] != 0){
ans += (n - i + 1) * dup[i];
//This inner loop
for(int j = i; j < n; j++){
dup[j] -= dup[i];
}
}
}
cout << ans << "n";
}
return 0;
While I was able to get the correct result by replacing the inner loop with transform function ,but I am not able to understand why doesn’t this work .The code gives the same answer even after I remove the inner loop ,as if the inner loop is not even doing anything.
I am not a expert or something in codeforces but I have solved a good amount of problems involving loops and arrays ,here I am really clueless about the issue .
Could someone help me understand why the first version of the code doesn’t produce the correct result? Is there a logical error in how I am updating the dup vector?
Also this the transform function which I am talking about :-
transform(dup.begin() + i, dup.end(), dup.begin() + i,
[value = dup[i]](int x) { return x - value; });
AyushRaj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.