-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStoneGame.java
40 lines (27 loc) · 1.11 KB
/
StoneGame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Solution {
public boolean stoneGame(int[] piles) {
int totalCount = 0;
for(Integer pile: piles) {
totalCount += pile;
}
Integer[][] memo = new Integer[piles.length][piles.length];
return stoneGame(piles, 0, 0, 1, memo) > 0;
}
private int stoneGame(
int[] piles,
int left,
int right,
int isAlexTurn,
Integer[][] memo
) {
if (left == right) return piles[left] * isAlexTurn;
if (memo[left][right] != null) return memo[left][right];
int maxScore = Integer.MIN_VALUE;
int subScore = stoneGame(piles, left + 1, right, -1*isAlexTurn, memo) + piles[left] * isAlexTurn;
maxScore = Math.max(maxScore, subScore);
subScore = stoneGame(piles, left, right - 1, -1*isAlexTurn, memo) + piles[right] * isAlexTurn;
maxScore = Math.max(maxScore, subScore);
memo[left][right] = maxScore;
return maxScore;
}
}