2 Player and N Coin

时间:2022-08-04 20:37:19
 class Solution {

     public void printChoices(int[] A, int[][] C) {
System.out.println("硬币列表如下:");
for(int i=0,l=A.length; i<l; i++) {
System.out.print(A[i] + "\t");
}
System.out.println("");
final int N = C.length;
String[] names = {"本人", "对手"};
int L = 0, R = N-1, WHO = 0;
while(L<=R) {
int c = C[L][R];
System.out.println(names[WHO] + "选择第 " + c + " 个元素" + A[c]);
WHO = (WHO+1)%2;
if(L==c) {
L = L+1;
}
if(R==c) {
R = R-1;
}
if(L == R) {
break;
}
}
} public int maxMoney(int[] A) {
final int N = A.length;
int[][] C = new int[N][N];
int[][] M = new int[N][N]; // 每个子问题最优解(赚的最多钱) // 设M(i,j) 为从第i到第j个硬币中能获得的最大收入
// j-i>=2 时
// M(i,j) = max(
// A[i] + min(M(i+2,j), M(i+1,j-1)),
// A[j] + min(M(i+1,j-1), M(i,j-2)),
// ); // 初始化坐标 [i,i] 和 [i,i+1] 处的决策和最大收入
for(int i=0; i<N; i++) {
M[i][i] = A[i];
C[i][i] = i;
if(i<N - 1) {
M[i][i+1] = Integer.max(A[i], A[i+1]);
C[i][i+1] = (A[i] < A[i+1] ? i+1 : i);
}
} // 计算所有 [i,i+2] [i,i+3]... 处的决策和最大收入
for(int i=N-2; i>=0; i--) {
for(int j=i+2; j<N; j++) {
int I = A[i] + Integer.min(M[i+2][j], M[i+1][j-1]);
int J = A[j] + Integer.min(M[i+1][j-1], M[i][j-2]);
M[i][j] = Integer.max(I, J);
C[i][j] = I>J ? i : j;
}
} printChoices(A, C);
return M[0][N-1];
} public static void main(String[] args) {
Solution s = new Solution();
int[] a = {1,20,10,2};
int r = s.maxMoney(a);
System.out.println(r);
}
}