Skip to content

Commit 11218a3

Browse files
committed
feat: solve No.486
1 parent 165c407 commit 11218a3

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Diff for: 401-500/486. Predict the Winner.md

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# 486. Predict the Winner
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Array, Math, Dynamic Programming, Recursion, Game Theory.
5+
- Similar Questions: Can I Win.
6+
7+
## Problem
8+
9+
You are given an integer array `nums`. Two players are playing a game with this array: player 1 and player 2.
10+
11+
Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of `0`. At each turn, the player takes one of the numbers from either end of the array (i.e., `nums[0]` or `nums[nums.length - 1]`) which reduces the size of the array by `1`. The player adds the chosen number to their score. The game ends when there are no more elements in the array.
12+
13+
Return `true` if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return `true`. You may assume that both players are playing optimally.
14+
15+
 
16+
Example 1:
17+
18+
```
19+
Input: nums = [1,5,2]
20+
Output: false
21+
Explanation: Initially, player 1 can choose between 1 and 2.
22+
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).
23+
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
24+
Hence, player 1 will never be the winner and you need to return false.
25+
```
26+
27+
Example 2:
28+
29+
```
30+
Input: nums = [1,5,233,7]
31+
Output: true
32+
Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.
33+
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
34+
```
35+
36+
 
37+
**Constraints:**
38+
39+
40+
41+
- `1 <= nums.length <= 20`
42+
43+
- `0 <= nums[i] <= 107`
44+
45+
46+
47+
## Solution
48+
49+
```javascript
50+
/**
51+
* @param {number[]} nums
52+
* @return {boolean}
53+
*/
54+
var PredictTheWinner = function(nums) {
55+
return maxDiff(nums, 0, nums.length - 1) >= 0;
56+
};
57+
58+
var maxDiff = function(nums, left, right) {
59+
if (left === right) return nums[left];
60+
return Math.max(
61+
nums[left] - maxDiff(nums, left + 1, right),
62+
nums[right] - maxDiff(nums, left, right - 1),
63+
);
64+
};
65+
```
66+
67+
**Explain:**
68+
69+
nope.
70+
71+
**Complexity:**
72+
73+
* Time complexity : O(n ^ 2).
74+
* Space complexity : O(n ^ 2).

0 commit comments

Comments
 (0)