The problem consists in choosing the best option at every moment of the game following these rules:
You can only pick the leftmost or the rightmost card.
Build the solution out from the simplest cases using recursion.
Let D
be the array of cards. Let A
be the total of your cards and B
be the total of your opponent's cards. Set S = A-B
to be the value of the game. You win if S>0
, lose if S<0
and tie if S==0
.
The easiest is to make two moves at once, your move followed by the opponent's determined move. There are two base cases to consider:
If length(D) == 0
, return S
. The game has ended.
If length(D) == 1
, return S + D[0]
. You choose the remaining card, and the game ends.
For the recursive case, when length(D) > 1
, evaluate the two possibilities
Let L
be the result of the game if you choose the left card followed by the opponent doing his deterministic move, i.e.
L = D[0] - max(D[1],D[N-1]) + cardGameValue(newD)
Let R
be the result of the game if you choose the right card followed by the opponent doing his deterministic move, i.e.
R = D[N-1] - max(D[0],D[N-2]) + cardGameValue(newD)
Choose the play corresponding to the larger number, i.e. take D[0]
if L>=R
, otherwise take D[N-1]
. Here N = length(D)
.