-2

You are given an array containing n elements, where n is odd. In one operation, you can select an index i, such that 1 ≤ i < n and remove ai and ai+1 from the array and concatenate the remaining array. You have to keep doing the operation until there are only 3 elements remaining in the array, say x, y and z. The objective is to do the operation in such a way that the sum x+y+z of the remaining 3 elements is maximized. Report the maximum sum you can obtain after doing the operations in any order.

I tried brute force but I am looking for a optimal solution

1 Answer 1

1

First of all, the order of deletion makes no difference. If we delete a_i and a_j, there is no difference in performing deletion on a_i or a_j first. (Theorem 1)

From Theorem 1, we can consider our deletion from the end of the array to begin.

For the Array[0..n-1], we consider element Array[n-1], there are two choices:

  1. Delete array[n-1] by perform deletion on array[n-2]
  2. Keep array[n-1] then goes to array[n-2]

So we define:

Sol(n, k) is the maximum answer by keeping k numbers in array[0..n]

Then we have:

Sol(n, k) = max(
  Sol(n - 1, k - 1) + array[n] # keep array[n]
  , Sol(n - 2, k) # delete both array[n] and array[n-1]
)

You can check my code for details:

ANS_MAX = 10**100


def sol(numbers):
    mem = {}

    def _sol(n, k):
        if mem.get((n, k)) is not None:
            return mem.get((n, k))
        if k == 0:
            return 0
        if n < 0:
            return -ANS_MAX
        ans = max(_sol(n - 2, k), _sol(n - 1, k - 1) + numbers[n])
        mem[(n, k)] = ans
        return ans

    return _sol(len(numbers) - 1, 3)


print(sol([1, 1, 1]))
print(sol([1, 1, 1, 1, 9, -9, 9]))

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.