原题链接在这里:https://leetcode.com/problems/stone-game/

题目:

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: [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.

Note:

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

题解:

There are even number of piles.

Person A picks first, he could either pick all the odd index piles or even index piles.

Thus, A could choose a larger one so the person pick first always win.

Use DP, dp[i][j] means largest sum from pile i to pile j. It could be obtained from either choosing piles[i] - dp[i+1][j], since dp[i+1][j] is the other player's turn. Or choosing pile[j] - dp[i][j-1].

Time Complexity: O(n^2). n = piles.length.

Space: O(n^2).

AC Java:

 class Solution {
public boolean stoneGame(int[] piles) {
int n = piles.length;
int [][] dp = new int[n][n];
for(int i = 0; i<n; i++){
dp[i][i] = piles[i];
} for(int size = 1; size<n; size++){
for(int i = 0; i+size<n; i++){
dp[i][i+size] = Math.max(piles[i]-dp[i+1][i+size], piles[i+size]-dp[i][i+size-1]);
}
} return dp[0][n-1] > 0;
}
}

类似Predict the Winner.

跟上Stone Game II.

最新文章

  1. 浅谈Java五大设计原则之代理模式
  2. C# winform多线程的小例子
  3. Oracle常用日期函数
  4. Term_Application
  5. 让less编译通过css滤镜
  6. JS 操作JSON字符串
  7. Android JNI之调用JAVA方法的返回类型签名
  8. Jquery-DataTable 使用介绍
  9. Python中字符串切片操作
  10. ViewTreeObserver简介
  11. @font-face(css3属性)实如今网页中嵌入随意字体
  12. coco2d-x 基于视口的地图设计
  13. 配置mac自带的Apache服务器
  14. Shell编程(week4_day4)--技术流ken
  15. windows下启动和运行分布式消息中间件消息队列 kafka
  16. Python学习第十二篇——切片的使用
  17. CentOS7安装Java还是无法使用javac
  18. 修改Nginx的header伪装服务器
  19. 关于Haxe3新特性“内联构造方法”的解释
  20. windows下使用python的scrapy爬虫框架,爬取个人博客文章内容信息

热门文章

  1. 手撕面试官系列(十):面试必备之常问Dubbo29题+MySQL55题
  2. 微信公众号开发 token 验证程序
  3. delphi xe6 窗口 visible 不能隐藏 解决
  4. docker redis4.0集群搭建
  5. 关于如何控制一个页面的Ajax读数据只读一次的简单解决办法!
  6. Ubuntu中安装(升级)GraphicsMagick
  7. Java知识回顾 (17)MySQL链接
  8. 【转载】 C#中decimal.TryParse方法和decimal.Parse方法的异同之处
  9. 笔谈 cocoapods的安装与使用
  10. Python学习日记(三十二) hmac检验客户端的合法性和socketsever模块