Can someone explain why is my code giving wrong answer, the logic seems right to me


#1

int Solution::solve(vector &A, int B) {
int sm=0;
int i=0,j=A.size()-1;
while(B-- and i<=j){
if(A[i]>A[j]){
sm+=A[i];
i++;
}else{
sm+=A[j];
j–;
}
}
return sm;
}


#2

yes man, i also applied same approach but dont know why this is failing for some test cases.


#3

Your code will not give the correct output. Consider the following test case: A = [5, -5, 1000, 500, 2, 2, 2] and B = 4