-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode486.java
More file actions
34 lines (30 loc) · 973 Bytes
/
LeetCode486.java
File metadata and controls
34 lines (30 loc) · 973 Bytes
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
public class LeetCode486 {
public static void main(String[] args) {
// 输入:nums = [1,5,2]
// 输出:false
System.out.println(new Solution486().predictTheWinner(new int[] { 1, 5, 2 }));
// 输入:nums = [1,5,233,7]
// 输出:true
System.out.println(new Solution486().predictTheWinner(new int[] { 1, 5, 233, 7 }));
}
}
class Solution486 {
Integer[][] dp;
public boolean predictTheWinner(int[] piles) {
dp = new Integer[piles.length][piles.length];
return score(piles, 0, piles.length - 1) >= 0;
}
public int score(int[] piles, int l, int r) {
if (dp[l][r] != null) {
return dp[l][r];
}
int result;
if (l == r) {
result = piles[l];
} else {
result = Math.max(piles[l] - score(piles, l + 1, r), piles[r] - score(piles, l, r - 1));
}
dp[l][r] = result;
return result;
}
}