Optimal Array Game
Alice and Bob play a game with an array of N positive integers. They take turns playing, with Alice going first.
On a player's turn, they must remove either the first element or the last element of the remaining array, and add its value to their total score. The game ends when the array becomes empty.
Both players play optimally to maximize their own score minus their opponent's score. Find the maximum possible difference between Alice's final score and Bob's final score (i.e., Alice's Score - Bob's Score).
Example 1:
Input: n = 4 , a = [4, 2, 9, 7]
Output: 6
Explanation: Optimal play:
- Alice picks 7
- Bob picks 9
- Alice picks 4
- Bob picks 2
Scores:
Alice = 7 + 4 = 11 Bob = 9 + 2 = 11 Difference = 0 (not optimal)
Better strategy:
- Alice picks 4
- Bob forced differently → leads to better result
Final optimal difference = 6
Example 2:
Input: n = 1 , a = [10]
Output: 10
Explanation : Alice picks the 10 and the difference is hence of 10
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Example 3:
Input : n = 5 , a = [1, 1, 5, 7, 10]
Constraints:
- 1 ≤ N ≤ 3000
- 1 ≤ a[i] ≤ 109