There are n coins in a line. (Assume n is even). Two players take turns to take a coin
from one of the ends of the line until there are no more coins left. The player with the larger amount of money wins.
1. Would you rather go first or second? Does it matter?
2. Assume that you go first, describe an algorithm to compute the maximum amount of money you can win.
[code]
import java.util.*;
public class Solution {
public static void main(String[] args)
{
int []array={3,2,2,3,1,2};
Solution s=new Solution(array);
s.coin(array, 0, array.length-1);
s.print();
}
int dp[][];
Solution(int[] array)
{
dp=new int[array.length][array.length];
for(int i=0;i<dp.length;i++)Arrays.fill(dp[i], -1);
}
void print()
{
for(int i=0;i<dp.length;i++)
{
for(int j=i;j<dp[0].length;j++)System.out.print(dp[i][j]+"\t");
System.out.println();
}
}
int coin(int[] array, int start, int end)
{
if(start>end)return 0;
if( dp[start][end]==-1 )
{
int p1 = array[start] + Math.min( coin( array, start+2, end ) , coin( array, start+1, end-1 ) );
int p2 = array[end] + Math.min( coin( array, start+1, end-1 ) , coin( array, start, end-2 ) );
dp[start][end] = Math.max( p1, p2 );
}
return dp[start][end];
}
}
[Thoughts]
这里的解法是以对手很聪明为前提:
p( i, j ) = max ( A[i] + min ( p(i+2, j), p(i+1, j-1) ), A[j] + min( p(i, j-2), p(i+1, j-1) ) ).