Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. class Solution {
  2.   Integer[] dp;
  3.   int[] stones;
  4.   public String stoneGameIII(int[] stoneValue) {
  5.     this.stones = stoneValue;
  6.     int total = 0;
  7.     for (int s : stoneValue) {
  8.       total += s;
  9.     }
  10.     dp = new Integer[stoneValue.length];
  11.     int aliceShare = solve(0);
  12.     int bobShare = total - aliceShare;
  13.     if (aliceShare > bobShare) {
  14.       return "Alice";
  15.     } else if (bobShare > aliceShare) {
  16.       return "Bob";
  17.     }
  18.     return "Tie";
  19.   }
  20.  
  21.   public int solve(int index) {
  22.     if (index >= stones.length) {
  23.       return 0;
  24.     }
  25.     if (dp[index] != null) {
  26.       return dp[index];
  27.     }
  28.    
  29.     int sum = stones[index];
  30.     int best = sum + minSolve(index + 1);
  31.     for (int i = index + 1; i < Math.min(stones.length, index + 3); i++) {
  32.       sum += stones[i];
  33.       best = Math.max(best, sum + minSolve(i + 1));
  34.     }
  35.    
  36.     dp[index] = best;
  37.     return best;
  38.   }
  39.  
  40.   public int minSolve(int index) {
  41.     if (index >= stones.length) {
  42.       return 0;
  43.     }
  44.     int worst = solve(index + 1);
  45.     for (int i = index + 2; i <= Math.min(stones.length, index + 3); i++) {
  46.       worst = Math.min(worst, solve(i));
  47.     }
  48.     return worst;
  49.   }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement