其他分享
首页 > 其他分享> > LeetCode 1140. Stone Game II

LeetCode 1140. Stone Game II

作者:互联网

原题链接在这里:https://leetcode.com/problems/stone-game-ii/

题目:

Alex and Lee continue their games with piles of stones.  There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].  The objective of the game is to end with the most stones. 

Alex and Lee take turns, with Alex starting first.  Initially, M = 1.

On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M.  Then, we set M = max(M, X).

The game continues until all the stones have been taken.

Assuming Alex and Lee play optimally, return the maximum number of stones Alex can get.

Example 1:

Input: piles = [2,7,9,4,4]
Output: 10
Explanation:  If Alex takes one pile at the beginning, Lee takes two piles, then Alex takes 2 piles again. Alex can get 2 + 4 + 4 = 10 piles in total. If Alex takes two piles at the beginning, then Lee can take all three piles left. In this case, Alex get 2 + 7 = 9 piles in total. So we return 10 since it's larger. 

Constraints:

题解:

For the current play A, if 2*M could reach the end of piles array, then A get them all. 

Otherwise, A gets all - the minimum player could get. Cash value hash[i][M], which means max value from current i with value of M, in case of duplicate calculation.

Time Complexity: O(2^n). dfs takes time T(n). T(n) = O(1) + 2*M*T(n-x).

Space: O(n^2).

AC Java:

 1 class Solution {
 2     int [] sum;
 3     int [][] hash;
 4     
 5     public int stoneGameII(int[] piles) {
 6         int n = piles.length;
 7         sum = new int[n];
 8         sum[n-1] = piles[n-1];
 9         for(int i = n-2; i>=0; i--){
10             sum[i] = sum[i+1] + piles[i];
11         }
12         
13         hash = new int[n][n];
14         
15         return dfs(piles, 0, 1);
16     }
17     
18     private int dfs(int [] piles, int i, int M){
19         if(i+2*M >= piles.length){
20             return sum[i];
21         }
22         
23         if(hash[i][M] != 0){
24             return hash[i][M];
25         }
26         
27         int min = Integer.MAX_VALUE;
28         for(int x = 1; x<=2*M; x++){
29             min = Math.min(min, dfs(piles, i+x, Math.max(M, x)));
30         }
31         
32         // all the left stones - minimum stones the other player could get
33         hash[i][M] = sum[i]-min;
34         return hash[i][M];
35     }
36 }

类似877. Stone Game.

标签:stones,Stone,Alex,piles,int,sum,1140,II,return
来源: https://www.cnblogs.com/Dylan-Java-NYC/p/11434194.html