This is my code and i only get 2/10 cases

#include <bits/stdc++.h>

#include

using namespace std;

int main()

{

int n; cin >> n;

```
vector<int> p(n);
vector<int> r(n);
for(int i = 0; i < n; i++){
cin >> p[i];
}
for(int i = 0; i < n; i++){
cin >> r[i];
}
int commands = 0;
for(int i = 0; i < n; i++){
if(r[i] != p[i]){ // if the current temp is NOT PERFECT
//check if it's less than or greater than what it's supposed to be
int diff = abs(p[i]-r[i]);
if(r[i] > p[i]){
//cout << "The real temperature is " << r[i] << " and it is greater than the IDEAL temperature of " << p[i] << endl; //the current temp is GREATER than perfect
//first find how many consecutive stalls must be reduced as well
//find the smallest difference
//reduce all the stalls in that range by that smallest difference
//update the commands to add smallest_diff to it
//if we still have to reduce the current temp then reduce it
//update the commands to add the difference between current_temp and perfect temp
int smallest_diff = 100000020;
int update_until = i;
bool consec = false;
for(int l = i+1; l < n; l++){
if(r[l] > p[l]){
smallest_diff = min(r[l]-p[l], smallest_diff);
consec = true;
update_until = l;
}
else{
break;
}
}
smallest_diff = min(diff, smallest_diff);
if(consec){
//cout << "we will updated from " << r[i] << " to " << r[update_until] << " and we will add " << smallest_diff << endl;
for(int q = i; q <= update_until; q++){
r[q] -= smallest_diff;
}
commands+=smallest_diff;
}
if(r[i] > p[i]){
commands+=(r[i]-p[i]);
r[i] = p[i];
//cout << "there is still some left over to take down: " << r[i]-p[i] << endl;
}
} else {
//the current temp is LESS than perfect
//cout << "The real temperature is " << r[i] << " and it is less than the IDEAL temperature of " << p[i] << endl;
int smallest_diff = 100000020;
int update_until = i;
bool consec = false;
for(int l = i+1; l < n; l++){
if(r[l] < p[l]){
smallest_diff = min(p[l]-r[l], smallest_diff);
consec = true;
update_until = l;
}
else {
break;
}
}
smallest_diff = min(diff, smallest_diff);
if(consec){
//cout << "we will updated from " << r[i] << " to " << r[update_until] << " and we will add " << smallest_diff << endl;
for(int q = i; q <= update_until; q++){
r[q] += smallest_diff;
}
commands+=smallest_diff;
}
if(r[i] < p[i]){
commands+=(p[i]-r[i]);
r[i] = p[i];
}
}
}
}
for(int i = 0; i < n; i++){
cout << p[i] <<" ";
}
cout << endl;
for(int i = 0; i < n; i++){
cout << r[i] << " ";
}
cout << endl;
cout << commands;
return 0;
```

}

I need help understanding why?

My algorithm is to through the current temperatures and if it’s less than the ideal, then find how many consecutive temperatures are less than the ideal and decrease the temperatue with that amount of commands. Same for if the current temp is greater than the ideal. I don’t know why it doesnt work.