package leetcode;

/**
 * https://leetcode.com/problems/stone-game-ii/
 */
public class Problem1140 {
    public int stoneGameII(int[] piles) {
        return stoneGame(piles, 1, true, 0);
    }

    private static int stoneGame(int[] piles, int m, boolean alex, int index) {
        int answer = 0;
        for (int i = 1; i <= 2 * m; i++) {
            int sum = 0;
            for (int j = index; j < index + i && j < piles.length; j++) {
                sum += piles[j];
                int value = stoneGame(piles, Math.max(i, m), !alex, j + 1);
                if (alex) {
                    value += sum;
                    answer = Math.max(answer,  value);
                }
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem1140 prob = new Problem1140();
        System.out.println(prob.stoneGameII(new int[]{2, 7, 9, 4, 4})); // 10
//        System.out.println(prob.stoneGameII(new int[]{2, 3, 4})); // 5
//        System.out.println(prob.stoneGameII(new int[]{2})); // 2
//        System.out.println(prob.stoneGameII(new int[]{2, 3})); // 5
    }
}

@@ -12,16 +12,65 @@
 tcode;%0A%0A
+import java.util.HashMap;%0Aimport java.util.Map;%0A%0A
 /**%0A * h
@@ -198,131 +198,397 @@
     
-return stoneGame(piles, 1, true, 0);%0A    %7D%0A%0A    private static int stoneGame(int%5B%5D piles, int m, boolean alex, int index) %7B
+int totalSum = 0;%0A        for (int pile : piles) %7B%0A            totalSum += pile;%0A        %7D%0A        return stoneGame(piles, 1, 0, totalSum, new HashMap%3C%3E());%0A    %7D%0A%0A    private static int stoneGame(int%5B%5D piles, int m, int index, int totalSum, Map%3CString, Integer%3E memo) %7B%0A        String key = m + %22,%22 + index;%0A        if (memo.containsKey(key)) %7B%0A            return memo.get(key);%0A        %7D
 %0A   
@@ -810,16 +810,27 @@
  value =
+ totalSum -
  stoneGa
@@ -859,89 +859,38 @@
 m), 
-!alex, j + 1);%0A                if (alex) %7B%0A                    value += sum;%0A    
+j + 1, totalSum - sum, memo);%0A
     
@@ -944,34 +944,26 @@
             
-    %7D%0A    
+%7D%0A
         %7D%0A  
@@ -960,33 +960,54 @@
       %7D%0A        
-%7D
+memo.put(key, answer);
 %0A        return 
@@ -1112,16 +1112,90 @@
 1140();%0A
+        System.out.println(prob.stoneGameII(new int%5B%5D%7B2, 3, 9, 4%7D)); // 6%0A
         
@@ -1264,18 +1264,16 @@
 ; // 10%0A
-//
         
@@ -1335,18 +1335,16 @@
 ); // 5%0A
-//
         
@@ -1400,18 +1400,16 @@
 ); // 2%0A
-//
         
@@ -1464,20 +1464,110 @@
  3%7D)); // 5%0A
+        System.out.println(prob.stoneGameII(new int%5B%5D%7B6, 4, 2, 8, 1, 8, 6, 6, 2%7D)); // 24%0A
     %7D%0A%7D%0A

Update problem 1140