While loop not working but for loop working


#1

This works:
vector Solution::solve(vector &A) {
vector ans;
int high=A[A.size()-1];
ans.push_back(high);
for(int i=A.size()-2;i>=0;i–)
{
if(A[i]>high)
{
high=A[i];
ans.push_back(high);
}
}
return ans;
}
But why this isn’t working:
vector Solution::solve(vector &A) {
vector ans;
int high=A[A.size()-1];
ans.push_back(high);
int i=A.size()-2;
while(i>0)
{
if(A[i]>high)
{
high=A[i];
ans.push_back(high);
}
i–;
}
return ans;
}


#2

You should write while(i>=0) instead of while(i>0) as i=0 can be in answer but you are just ignoring it.