算法设计与应用基础:第十五周

来源:互联网 发布:java刷题app 编辑:程序博客网 时间:2024/06/07 02:16

486. Predict the Winner

DescriptionHintsSubmissionsSolutions
  • Total Accepted: 10295
  • Total Submissions: 23135
  • Difficulty: Medium
  • Contributors:sameer13

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: FalseExplanation: 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: TrueExplanation: 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.  

题解:用递归的思想,假如我要计算从i到j这一段Player1可以拿到最多的分是多少,考虑第一步,要么拿第i个要么拿第j个,此时当然是选择拿掉之后剩下的子序列Player2能拿的分尽可能少。不失一般性,假设拿走了第i个,那么在i+1到j这个序列中,Player2同样会考虑选择拿掉之后剩下的子序列Player1拿的分尽可能的少。所以对于Player1在i到j这个序列时,选择总和减去拿走之后的子序列的最多的分得到的差最大的那一个,用公式说明就是cal_max(i, j) = max(sum(i, j) - cal_max(i + 1, j), sum(i, j) - cal_max(i, j + 1))。简单来说就是选择拿掉Player2在剩下的子序列所能获得的最高分较小的那一端,用递归即可算出。代码如下: