Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from either end of the array followed by the player 2 and then player 1 and so on. Each time a player picks a number, that number will not be available for the next player. This continues until all the scores have been chosen. The player with the maximum score wins.

Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.

Example 1:

Input: [1, 5, 2]
Output: False
Explanation: Initially, player 1 can choose between 1 and 2.
If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2).
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
Hence, player 1 will never be the winner and you need to return False.

Example 2:

Input: [1, 5, 233, 7]
Output: True
Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.

Note:

  1. 1 <= length of the array <= 20.
  2. Any scores in the given array are non-negative integers and will not exceed 10,000,000.
  3. If the scores of both players are equal, then player 1 is still the winner.

Approach #1: DP. [Java]

class Solution {
public boolean PredictTheWinner1(int[] nums) {
int n = nums.length;
int[][] dp = new int[n+1][n+1];
for (int i = 0; i < n; ++i)
dp[i][i] = nums[i]; for (int len = 1; len <= n; ++len) {
for (int i = 0; i < n - len; ++i) {
int j = i + len;
dp[i][j] = Math.max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]);
}
} return dp[0][n-1] >= 0;
} public boolean PredictTheWinner(int[] nums) {
int n = nums.length;
int[] dp = new int[n+1]; for (int i = n-1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
if (i == j) {
dp[i] = nums[i];
} else {
dp[j] = Math.max(nums[i] - dp[j], nums[j] - dp[j-1]);
}
}
} return dp[n-1] >= 0;
}
}

  

Approach:

Using a two dimensional array dp[i][j] to save all the intermediate states. From step 1, we may see at least two ways of doing it. It just turned out that if we choose to save how much more score that the first-in-action player will earn from position i to j in the array, the code will be better in a couple of ways.

After we decide that dp[i][j] saves how much more scores that the first-in-action player will get from i to j than the second player, the next step is how we update the dp table from one states to the next. Going back to the question, each player can pick one number either from the left or the right end of the array. Suppose they are picking up numbers from position i to j in the array and it is player A's turn to pick the number now. If player A picks position i, player A will earn nums[i] score instantly. Then player B will choose from i + 1 to j. Please note that dp[i+1][j] already saves how much score that the first-in-action player will get from i + 1 to j than the second player. So it means that player B will eventually earn dp[i+1][j] more score from i+1 to j than player A. So if player A picks position i, eventually player A will get nums[i] - dp[i+1][j] more score than player B after they pick up all numbers. Similarly, if player A picks position j, player A will earn nums[i] - dp[i][j-1] more score than player B after they pick up all numbers. Since A is smart, A will always choose the max in those two options, so: dp[i][j] = Math.max(nums[i] - dp[i+1][j], nums[j] - dp[i][j-1]);

Now we have the recursive formula, the next step is to decide where it all starts. This step is easy because we can easily recognize that we can start from dp[i][i], where dp[i][i] = nums[i]. Then the process becomes a very commonly seen process to update the dp table. I promise that this is a very useful process. Everyone who is preparing for interviews should get comfortable with this process:

Using a 5*5 dp table as an example, where i is the row number and j is the column number. Each dp[i][j] corresponds to a block at row i, column j on the table. We may start from filling dp[i][j], which are all the diagonal blocks. I marked them as 1. Then we can see that each dp[i][j] dpends only on dp[i+1][j] and dp[i][j-1]. On the table, it means each block (i, j) only depends on  the block to its left (i, j - 1) and to its down (i + 1, j). So after filling all the blocks markes as 1, we can start to calculate those blocks marked as 2. After that, all blocks marked as 3 and so on.

1 2 3 4 5
  1 2 3 4
    1 2 3
      1 4
        1

So in my code, I always use len to denote how far the block is away from the diagonal. So len ranges from 1 to n-1. Remeber this is the outer loop. The inner loop is all valid i positions. After filling all the upper side of the table, we will get our answer at dp[0][n-1] (marked as 5). This is the end of my code.

However, we can improve our code in the aspect of space complexity. So far, we are using a n*n matrix so the space complexity if O(n^2). It actually can be improved to O(n). That can be done by changing our way of filling the table. We may use only one dimensional dp[i] and we start to fill the table at the bottom right corner where dp[4] = nums[4]. On the next step, we start to fill the second to the last line, where it starts from dp[3] = nums[3]. Then dp[4] = Math.max(nums[4] - dp[3], nums[3] - dp[4]).

486. Predict the Winner的更多相关文章

  1. LN : leetcode 486 Predict the Winner

    lc 486 Predict the Winner 486 Predict the Winner Given an array of scores that are non-negative inte ...

  2. 【LeetCode】486. Predict the Winner 解题报告(Python)

    [LeetCode]486. Predict the Winner 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

  3. LC 486. Predict the Winner

    Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from eith ...

  4. [LeetCode] 486. Predict the Winner 预测赢家

    Given an array of scores that are non-negative integers. Player 1 picks one of the numbers from eith ...

  5. 【leetcode】486. Predict the Winner

    题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...

  6. 随手练——博弈论入门 leetcode - 486. Predict the Winner

    题目链接:https://leetcode.com/problems/predict-the-winner/ 1.暴力递归 当前数组左边界:i,右边界:j: 对于先发者来说,他能取到的最大值是:max ...

  7. 486 Predict the Winner 预测赢家

    给定一个表示分数的非负整数数组. 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端拿取分数,然后玩家1拿,…….每次一个玩家只能拿取一个分数,分数被拿取之后不再可取.直到没有剩余分数 ...

  8. [leetcode] 486. Predict the Winner (medium)

    原题 思路: 解法一: 转换比较拿取分数多少的思路,改为考虑 player拿的分数为正,把Player2拿的视为负,加上所有分数,如果最后结果大于0则Player1赢. 思考得出递归表达式: max( ...

  9. Leetcode之动态规划(DP)专题-486. 预测赢家(Predict the Winner)

    Leetcode之动态规划(DP)专题-486. 预测赢家(Predict the Winner) 给定一个表示分数的非负整数数组. 玩家1从数组任意一端拿取一个分数,随后玩家2继续从剩余数组任意一端 ...

随机推荐

  1. 设置 UILabel 和 UITextField 的 Padding 或 Insets (理解UIEdgeInsets)

    转自http://unmi.cc/uilable-uitextfield-padding-insets 主要是理解下UIEdgeInsets在IOS UI里的意义. 靠,这货其实就是间隔,起个名字这么 ...

  2. centos 使用windows7 存储

    1. 在Windows7上创建一个带密码的用户,如disk 2. 创建一个文件夹,如 D:\centos-disk2 3. 选中此文件夹,点击上方的  共享 -> 特定用户, 添加disk用户, ...

  3. transform.rotation和GetComponent<Rigidbody>().MoveRotation

    同时在UPDATE和FIXED UPDATE中调整 旋转 并未出现闪,而是一直以UPDATE中的为准,可认为MoveRotation调用后在UPDATE中生效 using System.Collect ...

  4. Jquery的树插件jqxTreeGrid的使用小结(实现基本的增删查改操作)

    一.引入相应的js <link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" t ...

  5. Struts2拦截器概述

    --------------------siwuxie095 Struts2 拦截器概述 1.Struts2 框架封装的很多功能都在 Struts2 的拦截器中 2.Struts2 框架中有很多拦截器 ...

  6. nat转发

    http://www.revsys.com/writings/quicktips/nat.html https://www.alibabacloud.com/zh/product/nat?spm=a3 ...

  7. gnuc与ansic

    GNU c与标准c的区别 1) 零长度数组 struct var_data { int len; char data[0]; }test: int a; test.data -->a 2)cas ...

  8. Ubuntu 安装配置 nginx

    作者:任明旭链接:https://www.zhihu.com/question/46241604/answer/100788789来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注 ...

  9. sqlserver 2017 linux还原windows备份时的路径问题解决

    windows的备份由于路径问题,在Linux上会报错 File 'YourDB_Product' cannot be restored to 'Z:\Microsoft SQL Server\MSS ...

  10. MyEclipse不能自动编译解决办法总结

    yEclipse在debug模式下,有时会碰到修改的文件无法自动编译的问题,以下的方法可以逐一尝试一下. 1.确保:Project->build automatically 已经被选上. 2.p ...