LeetCode-877. Stone Game

网友投稿 257 2022-08-29

LeetCode-877. Stone Game

​​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: [5,3,4,5]Output: trueExplanation: 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.

Note:

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

题解:dp问题。dp[i][j]记录从piles[i]到plies[j]中Alex最多可以赢Lee的分数,每次i++后动态更新每个长度为i的区间内Alex可以赢的分数。

class Solution {public: bool stoneGame(vector& piles) { int n = piles.size(); vector< vector > dp(n, vector(n, 0)); for(int i = 0; i < n; i++){ dp[i][i] = piles[i]; } for(int i = 1; i < n; i++){ for(int j = 0; j < n - i; j++){ dp[j][j + i] = max(piles[j] - dp[j + 1][j + i], piles[j + i] - dp[j][j + i - 1]); } } return dp[0][n - 1] > 0; }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:100行代码实现MerkleTree!
下一篇:武磊获赛季首个助攻,还差点儿打破进球荒!(武磊连续两场破门,他在比赛中的表现如何?)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~