There are_n_coins in a line. 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.
Could you please decide the first player will win or lose?
If n is even. Is there any_hacky_algorithm that can decide whether first player will win or lose in O(1) memory and O(n) time?
2个字,没懂...具体看笔记...
迭代版:还是考虑当前取硬币的人最优
publicbooleanfirstWillWin(int[] values) {if (values ==null||values.length==0) {returnfalse; }int n =values.length;int[] sum =newint[n +1];// use suffix sum to quicky calculate coins value sum range from i to jfor (int i =1; i <= n; i++) { sum[i] = sum[i -1] + values[i -1]; }int[][] dp =newint[n][n];// init dp diagonal with coins valuesfor (int i =0; i < n; i++) { dp[i][i] = values[i]; }// fill the rest of dp using len, // becasue we need to fill the right upper side of the matrix, // so can't loop as usualfor (int len =2; len <= n; len++) {// iterate through all starting pointfor (int s =0; s + len <= n; s++) {int e = s + len -1;int curSum = sum[e +1] - sum[s]; dp[s][e] = curSum -Math.min(dp[s +1][e], dp[s][e -1]); } }return dp[0][n -1] > sum[n] /2;}