<?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>longest Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/longest/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/longest/</link>
	<description></description>
	<lastBuildDate>Mon, 29 Jun 2020 16:22:29 +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>longest Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/longest/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1493. Longest Subarray of 1&#8217;s After Deleting One Element</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Jun 2020 20:35:09 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6975</guid>

					<description><![CDATA[<p>Given a binary array&#160;nums, you should delete one element from it. Return the size of the longest non-empty subarray containing only 1&#8217;s&#160;in the resulting array.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/">花花酱 LeetCode 1493. Longest Subarray of 1&#8217;s After Deleting One Element</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1493. Longest Subarray of 1&#039;s After Deleting One Element - 刷题找工作 EP339" width="500" height="281" src="https://www.youtube.com/embed/lgN5zT6EYqs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a binary array&nbsp;<code>nums</code>, you should delete one element from it.</p>



<p>Return the size of the longest non-empty subarray containing only 1&#8217;s&nbsp;in the resulting array.</p>



<p>Return 0 if there is no such subarray.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,0,1]
<strong>Output:</strong> 3
<strong>Explanation: </strong>After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,1,1,0,1,1,0,1]
<strong>Output:</strong> 5
<strong>Explanation: </strong>After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1]
<strong>Output:</strong> 2
<strong>Explanation: </strong>You must delete one element.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,0,0,1,1,1,0,1]
<strong>Output:</strong> 4
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,0,0]
<strong>Output:</strong> 0
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^5</code></li><li><code>nums[i]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution 1: DP</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-1.png" alt="" class="wp-image-7006" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Preprocess:<br>l[i] := longest 1s from left side ends with nums[i], l[i] = nums[i] + nums[i] * l[i &#8211; 1]<br>r[i] := longest 1s from right side ends with nums[i], r[i] = nums[i] + nums[i] * r[i + 1]<br><br>Use each node as a bridge (ignored), the total number of consecutive 1s = l[i &#8211; 1] + r[i + 1].</p>



<p>ans = max{l[i-1] + r[i +1]}<br>Time complexity: O(n)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; l(n);
    vector&lt;int&gt; r(n);
    for (int i = 0; i &lt; n; ++i)
      l[i] = (i &gt; 0 ? l[i - 1] * nums[i] : 0) + nums[i];
    for (int i = n - 1; i &gt;= 0; --i)
      r[i] = (i &lt; n - 1 ? r[i + 1] * nums[i] : 0) + nums[i];
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      ans = max(ans, (i &gt; 0 ? l[i - 1] : 0) + 
                     (i &lt; n - 1 ? r[i + 1] : 0));
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: DP</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-2.png" alt="" class="wp-image-7007" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i][0] := longest subarray ends with nums[i] has no ones.<br>dp[i][0] := longest subarray ends with nums[i] has 1 one.<br>if nums[i] == 1: <br>  dp[i][0] = dp[i &#8211; 1][0] + 1<br>  dp[i][1] = dp[i &#8211; 1][1] + 1<br>if nums[i] == 0:<br>  dp[i][0] = 0<br>  dp[i][1] = dp[i &#8211; 1][0] + 1<br>Time complexity: O(n)<br>Space complexity: O(n) -&gt; O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    // dp[i][0] := longest subarray ends with nums[i-1] has no zeros.
    // dp[i][0] := longest subarray ends with nums[i-1] has 1 zero.
    vector&lt;vector&lt;int&gt;&gt; dp(n + 1, vector&lt;int&gt;(2));
    int ans = 0;
    for (int i = 1; i &lt;= n; ++i) {
      if (nums[i - 1] == 1) {
        dp[i][0] = dp[i - 1][0] + 1;
        dp[i][1] = dp[i - 1][1] + 1;
      } else {
        dp[i][0] = 0;
        dp[i][1] = dp[i - 1][0] + 1;
      }
      ans = max({ans, dp[i][0] - 1, dp[i][1] - 1});
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 3: Sliding Window</strong></h2>



<figure class="wp-block-image size-large"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-3.png" alt="" class="wp-image-7008" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/06/1493-ep339-3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>Maintain a sliding window l ~ r s.t sum(num[l~r]) &gt;= r &#8211; l. There can be <strong>at most</strong> one 0 in the window.<br>ans = max{r &#8211; l} for all valid windows.</p>



<p>Time complexity: O(n)<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int ans = 0;
    int sum = 0; // sum of nums[l~r].
    for (int l = 0, r = 0; r &lt; n; ++r) {
      sum += nums[r];
      // Maintain sum &gt;= r - l, at most 1 zero.
      while (l &lt; r &amp;&amp; sum &lt; r - l)
        sum -= nums[l++];
      ans = max(ans, r - l);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/">花花酱 LeetCode 1493. Longest Subarray of 1&#8217;s After Deleting One Element</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-1493-longest-subarray-of-1s-after-deleting-one-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 5. Longest Palindromic Substring</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Sep 2018 07:45:12 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n^2)]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3917</guid>

					<description><![CDATA[<p>Problem Given a string&#160;s, find the longest palindromic substring in&#160;s. You may assume that the maximum length of&#160;s&#160;is 1000. Example 1: Input: "babad" Output: "bab"&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/">花花酱 LeetCode 5. Longest Palindromic Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a string&nbsp;<strong>s</strong>, find the longest palindromic substring in&nbsp;<strong>s</strong>. You may assume that the maximum length of&nbsp;<strong>s</strong>&nbsp;is 1000.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "babad"
<strong>Output:</strong> "bab"
<strong>Note:</strong> "aba" is also a valid answer.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input:</strong> "cbbd"
<strong>Output:</strong> "bb"
</pre>
<h1><strong>Solution: DP</strong></h1>
<p>Try all possible i and find the longest palindromic string whose center is i (odd case) and i / i + 1 (even case).</p>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(1)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 16 ms, 8.7 MB
class Solution {
public:
  string longestPalindrome(string s) {
    const int n = s.length();
    auto getLen = [&amp;](int l, int r) {
      while (l &gt;= 0 &amp;&amp; r &lt; n 
             &amp;&amp; s[l] == s[r]) {
        --l;
        ++r;
      }
      return r - l - 1;
    };
    int len = 0;
    int start = 0;
    for (int i = 0; i &lt; n; ++i) {
      int cur = max(getLen(i, i), 
                    getLen(i, i + 1));
      if (cur &gt; len) {
        len = cur;
        start = i - (len - 1) / 2;
      }
    }
    return s.substr(start, len);
  }
};</pre><p></div></div></p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, 6 ms， 36.5 MB
class Solution {
  public String longestPalindrome(String s) {
    int len = 0;
    int start = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      int cur = Math.max(getLen(s, i, i), 
                         getLen(s, i, i + 1));
      if (cur &gt; len) {
        len = cur;
        start = i - (cur - 1) / 2;
      }
    }
    return s.substring(start, start + len);
  }
  
  private int getLen(String s, int l, int r) {
    while (l &gt;= 0 &amp;&amp; r &lt; s.length() 
           &amp;&amp; s.charAt(l) == s.charAt(r)) {
      --l;
      ++r;
    }
    return r - l - 1;
  }
}</pre><p></div></div></p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, 812 ms, 12.7MB
class Solution:
  def longestPalindrome(self, s: str) -&gt; str:
    n = len(s)
    def getLen(l, r):
      while l &gt;= 0 and r &lt; n and s[l] == s[r]:
        l -= 1
        r += 1
      return r - l - 1
    
    start = 0
    length = 0    
    for i in range(n):      
      cur = max(getLen(i, i),
                getLen(i, i + 1))
      if cur &lt;= length: continue
      length = cur
      start = i - (cur - 1) // 2
    return s[start : start + length]</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-5-longest-palindromic-substring/">花花酱 LeetCode 5. Longest Palindromic Substring</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-5-longest-palindromic-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 845. Longest Mountain in Array</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-845-longest-mountain-in-array/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-845-longest-mountain-in-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Jun 2018 17:02:36 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2891</guid>

					<description><![CDATA[<p>Problem 题目大意：找出最长的山形子数组。 https://leetcode.com/problems/longest-mountain-in-array/description/ Let&#8217;s call any (contiguous) subarray B (of A) a mountain if the following properties hold: B.length &#62;= 3 There exists some 0 &#60; i &#60; B.length -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-845-longest-mountain-in-array/">花花酱 LeetCode 845. Longest Mountain in Array</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>题目大意：找出最长的山形子数组。</p>
<p><a href="https://leetcode.com/problems/longest-mountain-in-array/description/">https://leetcode.com/problems/longest-mountain-in-array/description/</a></p>
<p>Let&#8217;s call any (contiguous) subarray B (of A) a <em>mountain</em> if the following properties hold:</p>
<ul>
<li><code>B.length &gt;= 3</code></li>
<li>There exists some <code>0 &lt; i &lt; B.length - 1</code> such that <code>B[0] &lt; B[1] &lt; ... B[i-1] &lt; B[i] &gt; B[i+1] &gt; ... &gt; B[B.length - 1]</code></li>
</ul>
<p>(Note that B could be any subarray of A, including the entire array A.)</p>
<p>Given an array <code>A</code> of integers, return the length of the longest <em>mountain</em>.</p>
<p>Return <code>0</code> if there is no mountain.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>[2,1,4,7,3,2,5]
<strong>Output: </strong>5
<strong>Explanation: </strong>The largest mountain is [1,4,7,3,2] which has length 5.
</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false "><strong>Input: </strong>[2,2,2]
<strong>Output: </strong>0
<strong>Explanation: </strong>There is no mountain.
</pre>
<p>&nbsp;</p>
<p><strong>Note:</strong></p>
<ol>
<li><code>0 &lt;= A.length &lt;= 10000</code></li>
<li><code>0 &lt;= A[i] &lt;= 10000</code></li>
</ol>
<h1><strong>Solution: DP</strong></h1>
<p>Three passes</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms
class Solution {
public:
  int longestMountain(vector&lt;int&gt;&amp; A) {
    vector&lt;int&gt; inc(A.size());
    vector&lt;int&gt; dec(A.size());
    for (int i = 1; i &lt; A.size(); ++i)
      if (A[i] &gt; A[i - 1]) inc[i] = inc[i - 1] + 1;
    for (int i = A.size() - 2; i &gt; 0; --i)
      if (A[i] &gt; A[i + 1]) dec[i] = dec[i + 1] + 1;
    int ans = 0;
    for (int i = 0; i &lt; A.size(); ++i)
      if (inc[i] &amp;&amp; dec[i])
        ans = max(ans, inc[i] + dec[i] + 1);    
    return ans &gt;= 3 ? ans : 0;
  }
};</pre><p>One pass</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 24 ms
class Solution {
public:
  int longestMountain(vector&lt;int&gt;&amp; A) {
    int inc = 0;
    int dec = 0;
    int ans = 0;
    for (int i = 1; i &lt; A.size(); ++i) {
      if (dec &amp;&amp; A[i] &gt; A[i - 1] || A[i] == A[i - 1]) 
        dec = inc = 0;
      inc += A[i] &gt; A[i - 1];
      dec += A[i] &lt; A[i - 1];
      if (inc &amp;&amp; dec)
        ans = max(ans, inc + dec + 1);
    }
    return ans &gt;= 3 ? ans : 0;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-845-longest-mountain-in-array/">花花酱 LeetCode 845. Longest Mountain in Array</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-845-longest-mountain-in-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 594. Longest Harmonious Subsequence</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-594-longest-harmonious-subsequence/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-594-longest-harmonious-subsequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 21 Mar 2018 03:33:59 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2248</guid>

					<description><![CDATA[<p>Problem https://leetcode.com/problems/longest-harmonious-subsequence/description/ 题目大意：找一个最长子序列，要求子序列中最大值和最小值的差是1。 We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1. Now, given&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-594-longest-harmonious-subsequence/">花花酱 LeetCode 594. Longest Harmonious Subsequence</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/longest-harmonious-subsequence/description/">https://leetcode.com/problems/longest-harmonious-subsequence/description/</a></p>
<p>题目大意：找一个最长子序列，要求子序列中最大值和最小值的差是1。</p>
<p>We define a harmonious array is an array where the difference between its maximum value and its minimum value is <b>exactly</b> 1.</p>
<p>Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible <a href="https://en.wikipedia.org/wiki/Subsequence">subsequences</a>.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,3,2,2,5,2,3,7]
<b>Output:</b> 5
<b>Explanation:</b> The longest harmonious subsequence is [3,2,2,2,3].
</pre>
<p><b>Note:</b> The length of the input array will not exceed 20,000.</p>
<h1><strong>Solution1: HashTable</strong></h1>
<p>Time complexity: O(n)<br />
Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 127 ms
class Solution {
public:
  int findLHS(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; counts;
    int ans = 0;
    for (int num : nums) {
      ++counts[num];      
      int l = counts[num - 1];
      int h = counts[num + 1];      
      if (l || h)
        ans = max(ans, counts[num] + max(l, h));
    }
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Running time: 109 ms
class Solution {
public:
  int findLHS(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; counts;
    int ans = 0;
    for (int num : nums) {
      const int c = ++counts[num];
      auto it1 = counts.find(num - 1);
      auto it2 = counts.find(num + 1);
      if (it1 != counts.end())
        ans = max(ans, c + it1-&gt;second);
      if (it2 != counts.end())
        ans = max(ans, c + it2-&gt;second);
    }
    return ans;
  }
};</pre><p></p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 102 ms
class Solution {
public:
  int findLHS(vector&lt;int&gt;&amp; nums) {
    unordered_map&lt;int, int&gt; counts;
    int ans = 0;
    for (int num : nums)
      ++counts[num];
    
    for (const auto&amp; p : counts) {
      auto it1 = counts.find(p.first - 1);
      auto it2 = counts.find(p.first + 1);
      if (it1 != counts.end())
        ans = max(ans, p.second + it1-&gt;second);
      if (it2 != counts.end())
        ans = max(ans, p.second + it2-&gt;second);
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-594-longest-harmonious-subsequence/">花花酱 LeetCode 594. Longest Harmonious Subsequence</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/hashtable/leetcode-594-longest-harmonious-subsequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 128. Longest Consecutive Sequence</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 03 Oct 2017 06:43:40 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[sequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=524</guid>

					<description><![CDATA[<p>&#160; Problem: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2],&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/">花花酱 LeetCode 128. Longest Consecutive Sequence</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/rc2QdQ7U78I?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>&nbsp;</p>
<p><strong>Problem:</strong></p>
<p>Given an unsorted array of integers, find the length of the longest consecutive elements sequence.</p>
<p>For example,<br />
Given <code>[100, 4, 200, 1, 3, 2]</code>,<br />
The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Return its length: <code>4</code>.</p>
<p>Your algorithm should run in O(<i>n</i>) complexity.</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Hashtable / Hashset</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1.png"><img class="alignnone size-full wp-image-528" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>&nbsp;</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2.png"><img class="alignnone size-full wp-image-527" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/128-ep80-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p><strong>Time complexity: O(n)</strong></p>
<p><strong>Space complexity: O(n)</strong></p>
<p><strong>Solution 1: </strong>C++ / online</p><pre class="crayon-plain-tag">class Solution {
public:
    int longestConsecutive(vector&lt;int&gt;&amp; nums) {
        unordered_map&lt;int, int&gt; h;
        int ans = 0;
        for (int num : nums) {
            if (h.count(num)) continue;
            
            auto it_l = h.find(num - 1);
            auto it_r = h.find(num + 1);
            
            int l = it_l != h.end() ? it_l-&gt;second : 0;
            int r = it_r != h.end() ? it_r-&gt;second : 0;
            int t = l + r + 1;
            
            h[num] = h[num - l] = h[num + r] = t;
            
            ans = max(ans, t);            
        }
        
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>Solution 2: C++ / offline</p><pre class="crayon-plain-tag">class Solution {
public:
    int longestConsecutive(vector&lt;int&gt;&amp; nums) {
        unordered_set&lt;int&gt; h(nums.begin(), nums.end());
        int ans = 0;
        for (int num : nums)            
            if (!h.count(num - 1)) {
                int l = 0;
                while (h.count(num++)) ++l;
                ans = max(ans, l);
            }
        return ans;
    }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/">花花酱 LeetCode 128. Longest Consecutive Sequence</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/hashtable/leetcode-128-longest-consecutive-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 687. Longest Univalue Path</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 01 Oct 2017 16:42:45 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[path]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=489</guid>

					<description><![CDATA[<p>题目大意：给你一棵二叉树，返回一条最长的路径，要求路径上所有的节点值都相同。 https://leetcode.com/problems/longest-univalue-path/description/ Problem:  Given a binary tree, find the length of the longest path where each node in the path has the same value. This&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/">花花酱 LeetCode 687. Longest Univalue Path</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/yX1hVhcHcH8?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>题目大意：给你一棵二叉树，返回一条最长的路径，要求路径上所有的节点值都相同。</p>
<p><a href="https://leetcode.com/problems/longest-univalue-path/description/">https://leetcode.com/problems/longest-univalue-path/description/</a></p>
<p><strong>Problem: </strong></p>
<p>Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.</p>
<p><b>Note:</b> The length of path between two nodes is represented by the number of edges between them.</p>
<p><b>Example 1:</b></p>
<p>Input:</p>
<pre class="crayon:false">              5
             / \
            4   5
           / \   \
          1   1   5
</pre>
<p>Output:</p>
<pre class="crayon:false">2
</pre>
<p><b>Example 2:</b></p>
<p>Input:</p>
<pre class="crayon:false">              1
             / \
            4   5
           / \   \
          4   4   5
</pre>
<p>Output:</p>
<pre class="crayon:false">2
</pre>
<p><b>Note:</b> The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.</p>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>DFS</p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1.png"><img class="alignnone size-full wp-image-494" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/10/687-ep78-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 69 ms
class Solution {
public:
    int longestUnivaluePath(TreeNode* root) {
        if (root == nullptr) return 0;
        int ans = 0;
        univaluePath(root, &amp;ans);
        return ans;
    }
private:
    int univaluePath(TreeNode* root, int* ans) {
        if (root == nullptr) return 0;
        int l = univaluePath(root-&gt;left, ans);
        int r = univaluePath(root-&gt;right, ans);
        int pl = 0;
        int pr = 0;
        if (root-&gt;left &amp;&amp; root-&gt;val == root-&gt;left-&gt;val) pl = l + 1;
        if (root-&gt;right &amp;&amp; root-&gt;val == root-&gt;right-&gt;val) pr = r + 1;
        *ans = max(*ans, pl + pr);
        return max(pl, pr);
    }
};</pre><p></div><h2 class="tabtitle">Java</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 12 ms
class Solution {
    private int ans;
    public int longestUnivaluePath(TreeNode root) {
        if (root == null) return 0;        
        this.ans = 0;
        univaluePath(root);
        return this.ans;
    }
    
    private int univaluePath(TreeNode root) {
        if (root == null) return 0;
        int l = univaluePath(root.left);
        int r = univaluePath(root.right);
        int pl = 0;
        int pr = 0;
        if (root.left != null &amp;&amp; root.val == root.left.val) pl = l + 1;
        if (root.right != null &amp;&amp; root.val == root.right.val) pr = r + 1;
        this.ans = Math.max(this.ans, pl + pr);
        return Math.max(pl, pr);
    }
}</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">"""
Author: Huahua
Runtime: 899 ms
"""
class Solution:
    def longestUnivaluePath(self, root):
        self.ans = 0
        self._univaluePath(root)
        return self.ans
    
    def _univaluePath(self, root):
        if root is None: return 0
        l = self._univaluePath(root.left) if root.left is not None else -1
        r = self._univaluePath(root.right) if root.right is not None else -1
        pl = l + 1 if l &gt;= 0 and root.val == root.left.val else 0
        pr = r + 1 if r &gt;= 0 and root.val == root.right.val else 0
        self.ans = max(self.ans, pl + pr)
        return max(pl, pr)</pre><p></div></div></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/tree/leetcode-124-binary-tree-maximum-path-sum/">花花酱 LeetCode 124. Binary Tree Maximum Path Sum</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/tree/leetcode-687-longest-univalue-path/">花花酱 LeetCode 687. Longest Univalue Path</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/tree/leetcode-687-longest-univalue-path/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
