|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +public class _877 { |
| 6 | + public static class Solution1 { |
| 7 | + /** |
| 8 | + * credit: https://leetcode.com/problems/stone-game/discuss/154660/Java-This-is-minimax-%2B-dp-(fully-detailed-explanation-%2B-generalization-%2B-easy-understand-code) |
| 9 | + * <p> |
| 10 | + * Suppose the ID for Alex is 1, that for Lee is 0 |
| 11 | + * Alex wants to maximize the score to win while Lee wants to minimize the score to win. |
| 12 | + * Each time, each player has two options to pick, we'll use recursion to find the most optimal choice for each of them. |
| 13 | + */ |
| 14 | + public boolean stoneGame(int[] piles) { |
| 15 | + int len = piles.length; |
| 16 | + int[][][] dp = new int[len + 1][len + 1][2]; |
| 17 | + for (int[][] arr : dp) { |
| 18 | + for (int[] num : arr) { |
| 19 | + Arrays.fill(num, -1); |
| 20 | + } |
| 21 | + } |
| 22 | + return recursion(dp, 0, len - 1, 1, piles) > 0; |
| 23 | + } |
| 24 | + |
| 25 | + private int recursion(int[][][] dp, int left, int right, int identifier, int[] piles) { |
| 26 | + if (left > right) { |
| 27 | + return 0; |
| 28 | + } |
| 29 | + if (dp[left][right][identifier] != -1) { |
| 30 | + return dp[left][right][identifier]; |
| 31 | + } |
| 32 | + int next = Math.abs(identifier - 1); |
| 33 | + if (identifier == 1) { |
| 34 | + dp[left][right][identifier] = Math.max(piles[left] + recursion(dp, left + 1, right, next, piles), piles[right] + recursion(dp, left, right - 1, next, piles)); |
| 35 | + } else { |
| 36 | + dp[left][right][identifier] = Math.min(-piles[left] + recursion(dp, left + 1, right, next, piles), -piles[right] + recursion(dp, left, right - 1, next, piles)); |
| 37 | + } |
| 38 | + return dp[left][right][identifier]; |
| 39 | + } |
| 40 | + } |
| 41 | +} |
0 commit comments