[leetcode]486. Predict the Winner
[leetcode]486. Predict the Winner
Analysis
唉—— [每天刷题并不难0.0]
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.
递归解决,第一个玩家的分数为+, 第二个玩家的分数为-,最后结果小于0则第二个玩家胜利,否则第一个玩家胜利
Implement
class Solution {
public:
bool PredictTheWinner(vector<int>& nums) {
return helper(nums, 0, nums.size()-1) >= 0;
}
int helper(vector<int>& nums, int b, int e){
if(b == e)
return nums[b];
else
return max(nums[b]-helper(nums, b+1, e), nums[e]-helper(nums, b, e-1));
}
};