<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>min-max Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/min-max/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/min-max/</link>
	<description></description>
	<lastBuildDate>Sun, 17 Jan 2021 22:11:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>min-max Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/min-max/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1728. Cat and Mouse II</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1728-cat-and-mouse-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1728-cat-and-mouse-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Jan 2021 22:10:36 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[memorization]]></category>
		<category><![CDATA[min-max]]></category>
		<category><![CDATA[top-down]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7994</guid>

					<description><![CDATA[<p>A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a&#160;grid&#160;of size&#160;rows x cols, where each&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1728-cat-and-mouse-ii/">花花酱 LeetCode 1728. Cat and Mouse II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>A game is played by a cat and a mouse named Cat and Mouse.</p>



<p>The environment is represented by a&nbsp;<code>grid</code>&nbsp;of size&nbsp;<code>rows x cols</code>, where each element is a wall, floor, player (Cat, Mouse), or food.</p>



<ul><li>Players are represented by the characters&nbsp;<code>'C'</code>(Cat)<code>,'M'</code>(Mouse).</li><li>Floors are represented by the character&nbsp;<code>'.'</code>&nbsp;and can be walked on.</li><li>Walls are represented by the character&nbsp;<code>'#'</code>&nbsp;and cannot be walked on.</li><li>Food is represented by the character&nbsp;<code>'F'</code>&nbsp;and can be walked on.</li><li>There is only one of each character&nbsp;<code>'C'</code>,&nbsp;<code>'M'</code>, and&nbsp;<code>'F'</code>&nbsp;in&nbsp;<code>grid</code>.</li></ul>



<p>Mouse and Cat play according to the following rules:</p>



<ul><li>Mouse&nbsp;<strong>moves first</strong>, then they take turns to move.</li><li>During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the&nbsp;<code>grid</code>.</li><li><code>catJump, mouseJump</code>&nbsp;are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.</li><li>Staying in the same position is allowed.</li><li>Mouse can jump over Cat.</li></ul>



<p>The game can end in 4 ways:</p>



<ul><li>If Cat occupies the same position as Mouse, Cat wins.</li><li>If Cat reaches the food first, Cat wins.</li><li>If Mouse reaches the food first, Mouse wins.</li><li>If Mouse cannot get to the food within 1000 turns, Cat wins.</li></ul>



<p>Given a&nbsp;<code>rows x cols</code>&nbsp;matrix&nbsp;<code>grid</code>&nbsp;and two integers&nbsp;<code>catJump</code>&nbsp;and&nbsp;<code>mouseJump</code>, return&nbsp;<code>true</code><em>&nbsp;if Mouse can win the game if both Cat and Mouse play optimally, otherwise return&nbsp;</em><code>false</code>.</p>



<p><strong>Example 1:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/12/sample_111_1955.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2
<strong>Output:</strong> true
<strong>Explanation:</strong> Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
</pre>



<p><strong>Example 2:</strong></p>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/09/12/sample_2_1955.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = ["M.C...F"], catJump = 1, mouseJump = 4
<strong>Output:</strong> true
</pre>



<p><strong>Example 3:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = ["M.C...F"], catJump = 1, mouseJump = 3
<strong>Output:</strong> false
</pre>



<p><strong>Example 4:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = ["C...#","...#F","....#","M...."], catJump = 2, mouseJump = 5
<strong>Output:</strong> false
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [".M...","..#..","#..#.","C#.#.","...#F"], catJump = 3, mouseJump = 1
<strong>Output:</strong> true
</pre>



<p><strong>Constraints:</strong></p>



<ul><li><code>rows == grid.length</code></li><li><code>cols = grid[i].length</code></li><li><code>1 &lt;= rows, cols &lt;= 8</code></li><li><code>grid[i][j]</code>&nbsp;consist only of characters&nbsp;<code>'C'</code>,&nbsp;<code>'M'</code>,&nbsp;<code>'F'</code>,&nbsp;<code>'.'</code>, and&nbsp;<code>'#'</code>.</li><li>There is only one of each character&nbsp;<code>'C'</code>,&nbsp;<code>'M'</code>, and&nbsp;<code>'F'</code>&nbsp;in&nbsp;<code>grid</code>.</li><li><code>1 &lt;= catJump, mouseJump &lt;= 8</code></li></ul>



<h2><strong>Solution: MinMax + Memoization</strong></h2>



<p>Time complexity: O(m^3 * n^3 * max(n, m))<br>Space complexity: O(m^3 * n^3) </p>



<p>state: [mouse_pos, cat_pos, turn]</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool canMouseWin(vector&lt;string&gt;&amp; grid, int catJump, int mouseJump) {         
    const int m = grid.size(), n = grid[0].size();        
    int mouse, cat, food;
    for (int pos = 0; pos &lt; m * n; ++pos)      
      switch (grid[pos / n][ pos % n]) {
        case 'M': mouse = pos; break;
        case 'C': cat = pos; break;
        case 'F': food = pos; break;
        default: break;
      }
    
    const vector&lt;pair&lt;int, int&gt;&gt; dirs{{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
    const int limit = m * n * 2;
    vector&lt;vector&lt;vector&lt;int&gt;&gt;&gt; seen(m*n, 
        vector&lt;vector&lt;int&gt;&gt;(m*n, vector&lt;int&gt;(limit + 1, -1)));
    function&lt;bool(int, int, int)&gt; dfs = 
      [&amp;](int mouse, int cat, int d) -&gt; bool {
        const bool isCat = d &amp; 1;
        if (cat == food || cat == mouse || d &gt;= limit) return isCat;
        if (mouse == food) return !isCat;
        int&amp; ans = seen[mouse][cat][d];
        if (ans != -1) return ans;
        const int cur = isCat ? cat : mouse;
        const int jumps = isCat ? catJump : mouseJump;
        for (const auto&amp; [dx, dy] : dirs)
          for (int j = 0; j &lt;= jumps; ++j) {
            const int x = (cur % n) + dx * j;
            const int y = (cur / n) + dy * j;
            const int pos = y * n + x;
            if (x &lt; 0 || x &gt;= n || y &lt; 0 || y &gt;= m || grid[y][x] == '#') break;            
            if (!dfs(isCat ? mouse : pos, isCat ? pos : cat, d + 1)) return ans = true; 
          }
      return ans = false;
    };
    return dfs(mouse, cat, 0);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1728-cat-and-mouse-ii/">花花酱 LeetCode 1728. Cat and Mouse II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1728-cat-and-mouse-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 877. Stone Game</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Jul 2018 04:53:23 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[min-max]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3354</guid>

					<description><![CDATA[<p>Problem 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&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/">花花酱 LeetCode 877. Stone Game</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/xJ1Rc30Pyes?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Alex and Lee play a game with piles of stones.  There are an even number of piles <strong>arranged in a row</strong>, and each pile has a positive integer number of stones <code>piles[i]</code>.</p>
<p>The objective of the game is to end with the most stones.  The total number of stones is odd, so there are no ties.</p>
<p>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.</p>
<p>Assuming Alex and Lee play optimally, return <code>True</code> if and only if Alex wins the game.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">[5,3,4,5]</span>
<strong>Output: </strong><span id="example-output-1">true</span>
<strong>Explanation: </strong>
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.
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>2 &lt;= piles.length &lt;= 500</code></li>
<li><code>piles.length</code> is even.</li>
<li><code>1 &lt;= piles[i] &lt;= 500</code></li>
<li><code>sum(piles)</code> is odd.</li>
</ol>
<p><img class="alignnone size-full wp-image-3385" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/877-ep213.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/877-ep213.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/877-ep213-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/877-ep213-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution 1: min-max (TLE)</strong></h1>
<p>Time complexity: O(2^n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: TLE 26/46 passed.
class Solution {
public:
  bool stoneGame(vector&lt;int&gt;&amp; piles) {
    return score(piles, 0, piles.size() - 1) &gt; 0;
  }
private:
  int score(const vector&lt;int&gt;&amp; piles, int l, int r) {
    if (l == r) return piles[l];
    return max(piles[l] - score(piles, l + 1, r),
               piles[r] - score(piles, l, r - 1));
  }
};</pre><p></p>
<h1><strong>Solution 2: min-max + memorization</strong></h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n^2)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 12 ms
class Solution {
public:
  bool stoneGame(vector&lt;int&gt;&amp; piles) {
    const int n = piles.size();
    m_ = vector&lt;vector&lt;int&gt;&gt;(n, vector&lt;int&gt;(n, INT_MIN));
    return score(piles, 0, n - 1) &gt; 0;
  }
private:
  vector&lt;vector&lt;int&gt;&gt; m_;
  int score(const vector&lt;int&gt;&amp; piles, int l, int r) {
    if (l == r) return piles[l];
    if (m_[l][r] == INT_MIN)
      m_[l][r] = max(piles[l] - score(piles, l + 1, r),
                     piles[r] - score(piles, l, r - 1));
    return m_[l][r];
  }
};</pre><p></p>
<h1><strong>Solution 3:  min-max + DP</strong></h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n^2)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 8 ms
class Solution {
public:
  bool stoneGame(vector&lt;int&gt;&amp; piles) {
    const int n = piles.size();
    // dp[i][j] := max(your_stones - op_stones) for piles[i] ~ piles[j]
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, 0));
    for (int i = 0; i &lt; n; ++i)
      dp[i][i] = piles[i];
    for (int l = 2; l &lt;= n; ++l)
      for (int i = 0; i &lt; n - l + 1; ++i) {
        int j = i + l - 1;
        dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]);
      }
    return dp[0][n - 1] &gt; 0;    
  }
};</pre><p>O(n) Space</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  bool stoneGame(vector&lt;int&gt;&amp; piles) {
    const int n = piles.size();
    // dp[i] := max(your_stones - op_stones) for piles[i] to piles[i + l - 1]
    vector&lt;int&gt; dp(piles);    
    for (int l = 2; l &lt;= n; ++l)
      for (int i = 0; i &lt; n - l + 1; ++i)       
        dp[i] = max(piles[i] - dp[i + 1], piles[i + l - 1] - dp[i]);
    return dp[0] &gt; 0;
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/">花花酱 LeetCode 486. Predict the Winner</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/">花花酱 LeetCode 877. Stone Game</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 464. Can I Win</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-464-can-i-win/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-464-can-i-win/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 04 Feb 2018 17:17:44 +0000</pubDate>
				<category><![CDATA[Recursion]]></category>
		<category><![CDATA[Search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[min-max]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1751</guid>

					<description><![CDATA[<p>题目大意：两个人从1到M中每次取出一个数加到当前的总和上，第一个达到或超过T的人获胜。问你第一个玩家能不能获胜。 In the &#8220;100 game,&#8221; two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-464-can-i-win/">花花酱 LeetCode 464. Can I Win</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/GNZIAbf0gT0?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：两个人从1到M中每次取出一个数加到当前的总和上，第一个达到或超过T的人获胜。问你第一个玩家能不能获胜。</p>
<p>In the &#8220;100 game,&#8221; two players take turns adding, to a running total, any integer from 1..10. The player who first causes the running total to reach or exceed 100 wins.</p>
<p>What if we change the game so that players cannot re-use integers?</p>
<p>For example, two players might take turns drawing from a common pool of numbers of 1..15 without replacement until they reach a total &gt;= 100.</p>
<p>Given an integer <code>maxChoosableInteger</code> and another integer <code>desiredTotal</code>, determine if the first player to move can force a win, assuming both players play optimally.</p>
<p>You can always assume that <code>maxChoosableInteger</code> will not be larger than 20 and <code>desiredTotal</code> will not be larger than 300.</p>
<p><b>Example</b></p><pre class="crayon-plain-tag">Input:
maxChoosableInteger = 10
desiredTotal = 11

Output:
false

Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is &amp;gt;= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p><img class="alignnone size-full wp-image-1759" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><img class="alignnone size-full wp-image-1758" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/02/464-ep165-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><b>Solution: Recursion with memoization </b></p>
<p>Time complexity: O(2^M)</p>
<p>Space complexity: O(2^M)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 19 ms (&lt;98.70%)
class Solution {
public:
  bool canIWin(int M, int T) {
    const int sum = M * (M + 1) / 2;
    if (sum &lt; T) return false;
    if (T &lt;= 0) return true;
    m_ = vector&lt;char&gt;(1 &lt;&lt; M, 0);
    return canIWin(M, T, 0);
  }
private:
  vector&lt;char&gt; m_; // 0: unknown, 1: won, -1: lost
  bool canIWin(int M, int T, int state) {
    if (T &lt;= 0) return false;
    if (m_[state]) return m_[state] == 1;
    for (int i = 0; i &lt; M; ++i) {
      if (state &amp; (1 &lt;&lt; i)) continue; // number i used      
      // The next player can not win, current player wins
      if (!canIWin(M, T - (i + 1), state | (1 &lt;&lt; i))) 
        return m_[state] = 1;
    }
    // Current player loses.
    m_[state] = -1;
    return false;
  }
};</pre><p>Java</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 20 ms
class Solution {
  private byte[] m_;
  public boolean canIWin(int M, int T) {
    int sum = M * (M + 1) / 2;
    if (sum &lt; T) return false;
    if (T &lt;= 0) return true;
    m_ = new byte[1 &lt;&lt; M];
    return canIWin(M, T, 0);
  }
  
  private boolean canIWin(int M, int T, int state) {
    if (T &lt;= 0) return false;
    if (m_[state] != 0) return m_[state] == 1;
    
    for (int i = 0; i &lt; M; ++i) {
      if ((state &amp; (1 &lt;&lt; i)) &gt; 0) continue;
      if (!canIWin(M, T - (i + 1), state | (1 &lt;&lt; i))) {
        m_[state] = 1;
        return true;
      }
    }
    m_[state] = -1;
    return false;
  }    
}</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 706 ms
"""
class Solution:
  def canIWin(self, M, T):
    def win(M, T, m, state):
      if T &lt;= 0: return False
      if m[state] != 0: return m[state] == 1
      for i in range(M):
        if (state &amp; (1 &lt;&lt; i)) &gt; 0: continue
        if not win(M, T - i - 1, m, state | (1 &lt;&lt; i)):
          m[state] = 1
          return True
      m[state] = -1
      return False
    
    s = M * (M + 1) / 2
    if s &lt; T: return False
    if T &lt;= 0: return True
    if s == T: return (M % 2) == 1
    
    m = [0] * (1 &lt;&lt; M)
    return win(M, T, m, 0)</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-464-can-i-win/">花花酱 LeetCode 464. Can I Win</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-464-can-i-win/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 486. Predict the Winner</title>
		<link>https://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/</link>
					<comments>https://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 25 Mar 2017 05:38:38 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Leetcode]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[min-max]]></category>
		<category><![CDATA[recursion]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=37</guid>

					<description><![CDATA[<p>Problem 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&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/">花花酱 LeetCode 486. Predict the Winner</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/g5wLHFTodm0?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>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.</p>
<p>Given an array of scores, predict whether player 1 is the winner. You can assume each player plays to maximize his score.</p>
<p><strong>Example 1:</strong><br />
Input: [1, 5, 2]<br />
Output: False<br />
Explanation: Initially, player 1 can choose between 1 and 2.<br />
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).<br />
So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.<br />
Hence, player 1 will never be the winner and you need to return False.</p>
<p><strong>Example 2:</strong><br />
Input: [1, 5, 233, 7]<br />
Output: True<br />
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.<br />
Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win.<br />
Note:<br />
1 &lt;= length of the array &lt;= 20.<br />
Any scores in the given array are non-negative integers and will not exceed 10,000,000.<br />
If the scores of both players are equal, then player 1 is still the winner.</p>
<p><img class="alignnone size-full wp-image-2768" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/03/486-ep185.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/03/486-ep185.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/03/486-ep185-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/03/486-ep185-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution 1: Recursion</strong></h1>
<p>Time complexity: O(2^n)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 67 ms
class Solution {
public:
  bool PredictTheWinner(vector&lt;int&gt;&amp; nums) {    
    return getScore(nums, 0, nums.size() - 1) &gt;= 0;
  }
private:  
  // Max diff (my_score - op_score) of subarray nums[l] ~ nums[r].
  int getScore(vector&lt;int&gt;&amp; nums, int l, int r) {
    if (l == r) return nums[l];
    return max(nums[l] - getScore(nums, l + 1, r), 
               nums[r] - getScore(nums, l, r - 1));    
  }
};</pre><p></p>
<h1><strong>Solution 2: Recursion + Memoization</strong></h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  bool PredictTheWinner(vector&lt;int&gt;&amp; nums) {
    m_ = vector&lt;vector&lt;int&gt;&gt;(nums.size(), vector&lt;int&gt;(nums.size(), INT_MIN));
    return getScore(nums, 0, nums.size() - 1) &gt;= 0;
  }
private:
  vector&lt;vector&lt;int&gt;&gt; m_;
  // Max diff (my_score - op_score) of subarray nums[l] ~ nums[r].
  int getScore(vector&lt;int&gt;&amp; nums, int l, int r) {
    if (l == r) return nums[l];    
    if (m_[l][r] != INT_MIN) return m_[l][r];
    m_[l][r] = max(nums[l] - getScore(nums, l + 1, r), 
                   nums[r] - getScore(nums, l, r - 1));
    return m_[l][r];
  }    
};</pre><p>DP version</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  bool PredictTheWinner(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, INT_MIN));
    for (int i = 0; i &lt; n; ++i)
      dp[i][i] = nums[i];
    for (int l = 2; l &lt;= n; ++l)
      for (int i = 0; i &lt;= n - l; ++i) {
        int j = i + l - 1;
        dp[i][j] = max(nums[i] - dp[i + 1][j], nums[j] - dp[i][j - 1]);
      }
    return dp[0][n - 1] &gt;= 0;
  }
};</pre><p></p>
<h1><strong>Related Problem</strong></h1>
<ul>
<li><a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-877-stone-game/">花花酱 LeetCode 877. Stone Game</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/">花花酱 LeetCode 486. Predict the Winner</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/leetcode/leetcode-486-predict-the-winner/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
