leetcode Predict the Winner

Description

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
2
3
4
5
6
Input: [1, 5, 2]
Output: False
Explanation: 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.

The original problem is here.

My Solution

I solve this problem in C++, as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
std::vector<std::vector<int> > dp(nums.size(), std::vector<int>(nums.size()));

vector<int> sum;
sum.push_back(nums[0]);
for(int i = 1; i < nums.size(); i++) {
sum.push_back(nums[i] + sum[i-1]);
}
for (int wide = 0; wide < nums.size(); ++wide) {
for(int left = 0; left + wide < nums.size(); ++left) {
int right = left + wide;
if (left == right) {
dp[left][right] = nums[left];
} else if (left == right-1) {
dp[left][right] = mymax(nums[left], nums[right]);
} else if (left < right-1) {
int leftMax = nums[left] + sum[right] - sum[left] - dp[left+1][right];
int rightMax = nums[right] + sum[right-1] - sum[left-1] - dp[left][right-1];
dp[left][right] = mymax(leftMax, rightMax);
}
}
}
int res = dp[0][nums.size()-1];
return 2*res >= sum[nums.size()-1];
}
int mymax(int i, int j) {
return i > j ? i : j;
}
};

Note

To solve the problem, use daynamic programming, dp[left][right] means the max value one can get from vector nums which begin with left index end with right index.


leetcode Predict the Winner
http://zhaoshuaijiang.com/2017/04/18/leetcode-Predict-the-Winner/
作者
shuaijiang
发布于
2017年4月18日
许可协议