Given an integer array `A`, I need to pick `B` elements from either left or right end of the array `A` to get maximum sum. If `B = 4`, then you can pick the first four elements or the last four elements or one from front and three from back etc.

Example input:

```py
A = [5, -2, 3, 1, 2]
B = 3

```

The correct answer is `8` (by picking `5` from the left, and `1` and `2` from the right).

My code:

```py
def solve(A, B):
    n = len(A)
    # track left most index and right most index i,j
    i = 0
    j = n-1
    Sum = 0
    B2 = B  # B for looping and B2 for reference it
    # Add element from front
    for k in range(B):
        Sum += A[k]

    ans = Sum
    # Add element from last
    for _ in range(B2):
       # Remove element from front
       Sum -= A[i]
       # Add element from last
       Sum += A[j]
       ans = max(ans, Sum)

    return ans

```

But the answer I get is `6`.