Predict the Winner
来源:互联网 发布:淘宝页面找不 编辑:程序博客网 时间:2024/06/07 20:53
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.
解决方案:设a[i]为第i个数字,sum[i]为前i项的和,dp[i][j]为从第i个到第j个数字为所有数字的情况下,玩家1能获得的最大分数。利用动态规划的方法:
dp[i][i]=a[i];
dp[i][j]=max{sum[j-1]-sum[i-1]-dp[i][j-1]+a[j], sum[j]-sum[i]-dp[i+1][j]+a[j]}。
最后如果dp[1][n]>=sum[n]/2,那么玩家1能赢。
代码如下:
class Solution {public: bool PredictTheWinner(vector<int>& nums) { int len=nums.size(); int i,j,s,temp0,temp1; int *sum=new int[len+1]; int **dp; double t0,t1; dp=new int*[len]; for(i=0;i<len;i++) { dp[i]=new int[len]; } sum[0]=0; for(i=0;i<len;i++) { sum[i+1]=sum[i]+nums[i]; dp[i][i]=nums[i]; } for(s=1;s<len;s++) { for(i=0;i<len-s;i++) { j=i+s; temp0=sum[j]-sum[i]-dp[i][j-1]+nums[j]; temp1=sum[j+1]-sum[i+1]-dp[i+1][j]+nums[i]; if(temp0>=temp1) dp[i][j]=temp0; else dp[i][j]=temp1; } } t0=(double)dp[0][len-1]; t1=(double)sum[len]/2; delete []sum; for(i=0;i<len;i++) delete []dp[i]; delete []dp; if(t0>=t1) return true; else return false; }};
0 0
- 486. Predict the Winner**
- 486. Predict the Winner
- 486. Predict the Winner
- Predict the winner
- 486. Predict the Winner
- Predict the Winner
- Predict the Winner
- Predict the Winner
- 486. Predict the Winner
- Predict the Winner
- 【486】 Predict the Winner
- 486. Predict the Winner
- Predict the Winner
- 486. Predict the Winner
- LeetCode12 Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- [leetcode] predict the winner
- react demo11 (添加组件事件处理)
- react整理二阶段学习笔记
- "=="和 equals 方法究竟有什么区别?
- 向量的叉积及其应用
- POJ 3207:Ikki's Story IV
- Predict the Winner
- 1009. Product of Polynomials (25)[C语言]
- 算法学习笔记--贪婪算法
- java 判断一个数组中的数值是否连续相邻
- C++:虚基类详解
- 关于学习 unity3D 的知识预储备
- 对pair进行排序
- 1011. World Cup Betting (20)[C语言]
- 搞定linux上MySQL编程(六):C语言编写MySQL程序(结)