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
原创粉丝点击