[Swift]LeetCode486. 預測贏家 | Predict the Winner
阿新 • • 發佈:2019-02-02
one 最大 nat runt 兩個 預測贏家 from ret left
Runtime: 12 ms Memory Usage: 3.9 MB
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:
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.
Example 2:
Input: [1, 5, 233, 7] Output: True Explanation: Player 1 first chooses 1. Then player 2 have to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233.Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.
Note:
- 1 <= length of the array <= 20.
- Any scores in the given array are non-negative integers and will not exceed 10,000,000.
- If the scores of both players are equal, then player 1 is still the winner.
給定一個表示分數的非負整數數組。 玩家1從數組任意一端拿取一個分數,隨後玩家2繼續從剩余數組任意一端拿取分數,然後玩家1拿,……。每次一個玩家只能拿取一個分數,分數被拿取之後不再可取。直到沒有剩余分數可取時遊戲結束。最終獲得分數總和最多的玩家獲勝。
給定一個表示分數的數組,預測玩家1是否會成為贏家。你可以假設每個玩家的玩法都會使他的分數最大化。
示例 1:
輸入: [1, 5, 2] 輸出: False 解釋: 一開始,玩家1可以從1和2中進行選擇。 如果他選擇2(或者1),那麽玩家2可以從1(或者2)和5中進行選擇。如果玩家2選擇了5,那麽玩家1則只剩下1(或者2)可選。 所以,玩家1的最終分數為 1 + 2 = 3,而玩家2為 5。 因此,玩家1永遠不會成為贏家,返回 False。
示例 2:
輸入: [1, 5, 233, 7] 輸出: True 解釋: 玩家1一開始選擇1。然後玩家2必須從5和7中進行選擇。無論玩家2選擇了哪個,玩家1都可以選擇233。 最終,玩家1(234分)比玩家2(12分)獲得更多的分數,所以返回 True,表示玩家1可以成為贏家。
註意:
- 1 <= 給定的數組長度 <= 20.
- 數組裏所有分數都為非負數且不會大於10000000。
- 如果最終兩個玩家的分數相等,那麽玩家1仍為贏家。
Runtime: 12 ms Memory Usage: 3.9 MB
1 class Solution { 2 func PredictTheWinner(_ nums: [Int]) -> Bool { 3 var nums = nums 4 var n:Int = nums.count 5 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:-1,count:n),count:n) 6 return canWin(&nums, 0, n - 1, &dp) >= 0 7 } 8 9 func canWin(_ nums:inout [Int],_ s:Int,_ e:Int,_ dp:inout [[Int]]) -> Int 10 { 11 if dp[s][e] == -1 12 { 13 dp[s][e] = (s == e) ? nums[s] : max(nums[s] - canWin(&nums, s + 1, e, &dp), nums[e] - canWin(&nums, s, e - 1, &dp)) 14 } 15 return dp[s][e] 16 } 17 }
[Swift]LeetCode486. 預測贏家 | Predict the Winner