Dynamic planning the first person each time choose the current + after the largest worth can get the first person to complete, the second person with the same strategy to take the remaining coins in the current + after the maximum value can be obtained with DP[I][J] recorded in the remaining v[i]~v[j], First take the person can take the maximum amount of money with Record[i][j] recorded in the left V[i]~v[j], first took the person chose which only I and j two kinds of possible when only 1 coins: dp[i][i] = v[i]//Can only take this, no suspense when only 2 coins: dp[i ][i + 1] = max (V[i], v[i + 1])//Be sure to select the largest when the remaining coins >=3, need to know the strategy of the second person: dp[i][j] = max (Take the first + second person selected after the remaining can get the maximum value, take the last + second The maximum value that can be obtained after a personal selection)
Public Static intMaxValue (int[]v,intN) { int[] DP =New intN [n];//record the maximum value that can be selected in I-j int[] record =New intN [n];//record the position of the selected value in the I-j, making the selected result the largest for(inti=0;i<n;i++) {Dp[i][i]=V[i]; Record[i][i]=i; } for(inti=2;i<=n;i++) {//traverse the current number of remaining coins!!!! Starting from two, 3, 4,,, until the length of N. for(ints=0; (s+i) <=n;s++) {//Start position Traversal inte=i+s-1;//until the end of the current intNum1=v[s],num2=v[e];//the value of the first and the end if(i>=3) {//Longer than 2 o'clock, consider the amount of money you can get from the remaining coins.//Suppose you take the first one if(record[s+1][e]==s+1)//The second person will take the rest of the first one insideNum1+=dp[s+2][e]; Else//The second one will take the last one in the rest .NUM1 +=dp[s+1][e-1]; //Suppose you take the last one if(record[s][e-1]==s)//Ibid .Num2 + = Dp[s+1][e-1]; Else //Ibid .Num2 +=dp[s][e-2]; } Record[s][e]= (num1>num2)? S:e;//in the selection of the length I, select the one with the large combined value as the selection target.dp[s][e]= (num1>num2) num1:num2;// } } for(inti=0;i<n;i++){ for(intj=0;j<n;j++) {System.out.print (Dp[i][j]+" "); } System.out.println (); } returnDp[0][n-1]; }
Dynamic planning selects coins to make the most value