JAVA | DP | 6% |
```\nclass Solution {\n    public int stoneGameVII(int[] stones) {\n        //strategy: DP\n        //precompute the sum\n        int sum = 0;\n        for (int
```\nclass Solution {\n    public int stoneGameVII(int[] stones) {\n        //strategy: DP\n        //precompute the sum\n        int sum = 0;\n        for (int stone : stones) {\n            sum += stone;\n        }\n        int n = stones.length;\n        Integer[][][] dp = new Integer[n][n][2];\n        return helper(stones, dp, 0, n - 1, sum, 0);\n    }\n    public int helper(int[] stones, Integer[][][] dp, int f, int b, int sum, int person) {\n        //reached base case\n        if (f > b) {\n            return 0;\n        }\n        //seen before\n        if (dp[f][b][person] != null) {\n            return dp[f][b][person];\n        }\n        //Alice is taking her turn\n        if (person == 0) {\n            //Alice chooses the first stone and gets the remaining sum\n            int x = helper(stones, dp, f + 1, b, sum - stones[f], 1) + (sum - stones[f]);\n            //Alice chooses the last stone and gets the remaining sum\n            int y = helper(stones, dp, f, b - 1, sum - stones[b], 1) + (sum - stones[b]);\n            //find max that Alice can get\n            return dp[f][b][person] = Math.max(x, y);\n        //Bob is taking his turn\n        } else {\n            //Bob chooses the first stone and gets the remaining sum\n            int x = helper(stones, dp, f + 1, b, sum - stones[f], 0) - (sum - stones[f]);\n            //Bob chooses the last stone and gets the remaining sum\n            int y = helper(stones, dp, f, b - 1, sum - stones[b], 0) - (sum - stones[b]);\n            //find min so that we can subtract from Alice\'s score\n            return dp[f][b][person] = Math.min(x, y);\n        }\n    }\n}
[]