# Swift刷LeetCode 之 877-Stone Game-Med

Alex and Lee play a game with piles of stones.  There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.

Alex and Lee take turns, with Alex starting first.  Each turn, a player takes the entire pile of stones from either the beginning or the end of the row.  This continues until there are no more piles left, at which point the person with the most stones wins.

Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.

Example 1:

Input: piles = [5,3,4,5]
Output: true
Explanation:
Alex starts first, and can only take the first 5 or the last 5.
Say he takes the first 5, so that the row becomes [3, 4, 5].
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.


Constraints:

• 2 <= piles.length <= 500
• piles.length is even.
• 1 <= piles[i] <= 500
• sum(piles) is odd.

Alex先出发，只能选前5个或后5个。

2 < =成堆。长度< = 500

1 <=成堆[i] <= 500

Idea1:

Since the length of the piles is even and the sum of the pildes is odd, which means the sum of stones taken by one people will always be greater than another and the first player can always pick odd piles or always pick even piles!

Alex is the first player and he choose stones with optimal strategy, he will always win under the situation.

Return true

Idea2:

Using the best strategy (he always picks the biggest one either from the start pile or the last pile) to calcualte the sum of stones that Alex could get, if the first pile of stones is greater than the last pile, Alex choose the head pile. Let Lee choose from the rest of piles of stones, meanwhile, he choose the smallest pile of stones. Calculate the score for Alex until there are no stones left. Return scoreAlex - scoreLee > 0 ? true : false

class Solution {
func stoneGame(_ piles: [Int]) -> Bool {
let sum = piles.reduce(0, +)
let scoreAlex = helper(piles,0)
let scoreLee = sum - scoreAlex
return scoreAlex - scoreLee > 0 ? true : false

}

func helper(_ piles: [Int],_ turn : Int) -> Int{
let first = 0
let last = piles.count - 1
if first == last {return 0}
if piles[first] > piles[last]{
if turn == 0{
return piles[first] + helper(Array(piles.dropFirst()), 1)
}
else{
return 0 + helper(piles.dropLast(), 0)
}

}
else{
if turn == 0{
return piles[last] + helper(piles.dropLast(), 1)
}
else{
return 0 + helper(Array(piles.dropFirst()), 0)
}
}
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

SheldonTT

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
07-29 797

02-10 1542
07-29 328