Let's play a game:
There are n stacks of coins in a row. i-th stack consists of d_i coins. Two players: Player1, Player2 make moves alternately. Player in his turn can only take first stack or last stack or both of them. The game ends when there are no coins left. Each player wants to have as many coins as possible at the end. Player1 starts.
I was wondering about algorithm (sounds like greedy algorithm) to count how many coins each player has at the end of the game when both plays optimal.
I don't have any idea how to approach such algorithms. Just guess strategy or there is some way to deduce it? Or maybe it's rather too weird problem to implement an algorithm?
Examples (coins in stacks from first to n-th):
1, 100, 1 - players have 2 and 100 coins respectively (unfortunately first player can only take first and last stack - second player will always take stack with 100 coins)
1, 1, 100, 1, 1, 5 - players have 8 and 101 coins respectively (I think this is after optimal game - first take 5 and 1, then second take 1 to prevent player1 from taking stack with 100 coins. If player1 take less than 6 coins in his first move, he will always have less than 8 coins).
I hope I specified enough the problem. Do you agree that it is interesting? :) Can anybody help?
Adding to @Peter's dynamic programming solution:
I think the recurrence would look somewhat like following:
Considering the coin stacks ranging from
A[i,..j]
Let,
dp[i, j]
represents the max score that Player1 can possibly get. Then,As there are only N^2 possible game states. It can be implemented by filling up a dp table of size N^2.
For C++ fans:
Also, as @Peter pointed out your analysis for 2nd example is wrong. Player1 actually has a strategy to win that game by scoring 102 coins.
You can solve this via dynamic programming in O(n^2) by solving the subproblem of what is the best strategy if only stacks in the range a to b-1 are present.
Python code:
This says that the optimal game for your second case is actually for the first person to take just the leftmost 1. From then on he can guarantee that he will capture the 100, so he wins.
(Player 1 wins 102, player 2 wins 7)
There are O(n^2) subgames so this algorithm takes time O(n^2)
The subgames (and optimal first player/second player coins) are:
So, for example, suppose that we have found all the optimal plays for the smaller games and wish to find the best play for [1,1,100,1,1,5].
All we do is consider each move in turn:
So the best move is to take the first stack only.