486. Predict the Winner

题目链接:https://leetcode.com/problems...

看了discussion里面参考的mit算法视频:https://www.youtube.com/watch...

recursion + memo 或者 iteration用dp table

public class Solution {
    public boolean PredictTheWinner(int[] nums) {
        // // even, always win
        // if(nums.length % 2 == 0) return true;
        
        int n = nums.length;
        // maximum score play1 can get
        int[][] dp = new int[n][n];
        int sum = 0;
        // base cases
        for(int i = 0; i < n; i++) {
            dp[i][i] = nums[i];
            sum += nums[i];
        }
        for(int i = 1; i < n; i++) dp[i-1][i] = Math.max(nums[i-1], nums[i]);
        
        // dp recur
        for(int i = n - 1; i >= 0; i--) {
            for(int j = i + 2; j <n; j++) {
                int a = Math.min(dp[i+1][j-1], dp[i+2][j]) + dp[i][i];
                int b = Math.min(dp[i][j-2], dp[i+1][j-1]) + dp[j][j];
                dp[i][j] = Math.max(a, b);
            }
        }
        
        return dp[0][n-1] >= sum - dp[0][n-1];
    }
}

lulouch13
13 声望6 粉丝