486. Predict the Winner
来源:互联网 发布:ubuntu配置内网ip 编辑:程序博客网 时间:2024/06/13 03:36
问题描述:
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.
给定一个游戏的分数数组,玩家1和玩家2只能从两端轮流取分数,玩家1先取,被取得数字不能再取第二次,即相当于从数组中删除,直到没有数字可取为止,游戏结束,分数和高的玩家胜利。
要预测玩家1是否可以胜利,可以胜利的话返回true,否则返回false。
假设玩家1和玩家2都会取使自己分数最大化的数字。
问题解决:
用一个二维数组 a[ i ][ j ]表示 数组的第 i 个元素到第 j 个元素作为被取的数组时,玩家1可以取到的最大分数和
当 i == j 时,若数组的长度是奇数,则a[ i ][ j ]=nums[ i - 1 ],因为轮到玩家1取,否则a[ i ][ j ]=0
当 j > i 时,若数组长度跟 j - i + 1即当前被取数组的长度奇偶性相同,则轮到玩家1取
a[ i ][ j ] = max( a[ i+1 ][ j ] + nums[i - 1], a[ i ][j - 1] + nums[j - 1])
否则轮到玩家2取,玩家2会使玩家1接下来取到的分数和最小化,即
a[ i ][ j ] = min( a[ i+1 ][ j ] , a[ i ][j - 1])
代码如下:
class Solution {
public:
int PredictTheWinner(vector<int>& nums) {
int all = 0;
int a[21][21];
int i, j;
int n = nums.size()%2;
//计算分数总和
for(i = 0; i < nums.size(); i++) {
all += nums[i];
}
//初始化a
for(i = 0; i < 21; i++) {
for(j = 0; j < 21; j++) {
a[i][j] = 0;
}
}
//当i==j时,对a进行赋值
for(i = 1; i <= nums.size(); i++) {
//若奇偶性相同则为数组中第i个数字,否则为0
if(n == 1) a[i][i] = nums[i-1];
else a[i][i] = 0;
}
//i表示被取的数组的长度,j从1开始遍历数组
for(i = 1; i < nums.size(); i++) {
for( j = 1; j < nums.size()-i+1; j++) {
//若奇偶性相同,取大的
if(n == (i+1)%2) a[j][i+j] = a[j+1][i+j]+nums[j-1] > a[j][i+j-1]+nums[i+j-1] ? a[j+1][i+j]+nums[j-1] : a[j][i+j-1]+nums[i+j-1];
//否则取小的
else a[j][i+j] = a[j+1][i+j] < a[j][i+j-1] ? a[j+1][i+j] : a[j][i+j-1];
}
}
//返回玩家1能取到的最大分数是否大于等于分数总和减去该分数
return a[1][nums.size()] >= all-a[1][nums.size()];
}
};
- 486. Predict the Winner**
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 486. Predict the Winner
- 171121 逆向-静态分析安卓(特殊类)
- SpringMVC参数传递 使用model完成页面的回显
- 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
- haproxy透传用户ip-方法和原理
- Frontend Architecture for Design Systems.pdf 英文原版 免费下载
- 486. Predict the Winner
- Linux常用命令4(基于Centos)
- android 图片任意裁剪(学习中)
- nginx
- C语言的32个关键字(2)
- 安卓绘制贝塞尔曲线
- 机器学习
- wdcp安装多版本php环境报错的解决方法
- An Enhanced Allocator——为C语言的动态内存分配添加出错预警