Anyone help me. What is the problem with this Approach?


#1

Comment body goes here.
What is the problem with this Approach?

int Solution::solve(vector &A, int B) {
int p1 = 0,p2 = A.size(),sum = 0;
while(B >= 0 && p1 <= p2) {
if(A[p1] >= A[p2]) {
sum += A[p1];
p1++;
B–;
}
else {
sum += A[p2];
p2–;
B–;
}
}
return sum;
}


#2

Your code is hard to understand. But let me tell you the approach to solve this.

maxSum = max(maxSum, sum[i] + sum[n-1] - sum[n-B + i]);

where sum[i] is sum till ith element. Also, you need to consider the case when no element is picked from the start.


#3

check for this testcase
1,-5,100,100,2,3,4,5
b=4;


#4

I understood the problem with my code. Thank you.