算法设计与应用基础:第十五周
来源:互联网 发布: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 <= length of the array <= 20.
- Any scores in the given array are non-negative integers and will not exceed 10,000,000.
- 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在剩下的子序列所能获得的最高分较小的那一端,用递归即可算出。代码如下:
阅读全文
0 0
- 算法设计与应用基础:第十五周
- 算法设计与应用基础:第十五周(2)
- 算法设计与结构基础作业第十五周
- 算法分析与设计第十五周
- 算法设计与应用基础-第二周
- 算法设计与应用基础:第三周
- 算法设计与应用基础-第三周
- 算法设计与应用基础-第五周
- 算法设计与应用基础:第五周
- 算法设计与应用基础-第六周
- 算法设计与应用基础:第六周
- 算法设计与应用基础:第七周
- 算法设计与应用基础-第七周
- 算法设计与应用基础-第八周
- 算法设计与应用基础:第八周
- 算法设计与应用基础:第九周
- 算法设计与应用基础:第十周
- 算法设计与应用基础-第十二周
- bzoj1731[Usaco2005 dec]Layout 排队布局 差分约束
- 一步一步学springboot (十二)不继承springboot父工程
- js笔记
- Linux内核0.11分析三之创建子进程
- linux常用命令之———批量建目录
- 算法设计与应用基础:第十五周
- 1033: 五级制成绩
- 使用PHP调用Mysql数据库函数封装,对数据库进行增删改查
- 特斯拉如何颠覆制造业
- Linux常用命令2
- Win7的字体存放路径
- 1034: 夏季促销
- CSS/移动端添加真正1PX边框线
- 使用PHP制作单文件上传