<?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>subsequence Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/subsequence/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/subsequence/</link>
	<description></description>
	<lastBuildDate>Thu, 24 Aug 2023 04:44:48 +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>subsequence Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/subsequence/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2825. Make String a Subsequence Using Cyclic Increments</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 24 Aug 2023 04:38:17 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subsequence]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10077</guid>

					<description><![CDATA[<p>You are given two&#160;0-indexed&#160;strings&#160;str1&#160;and&#160;str2. In an operation, you select a&#160;set&#160;of indices in&#160;str1, and for each index&#160;i&#160;in the set, increment&#160;str1[i]&#160;to the next character&#160;cyclically. That is&#160;'a'&#160;becomes&#160;'b',&#160;'b'&#160;becomes&#160;'c', and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/">花花酱 LeetCode 2825. Make String a Subsequence Using Cyclic Increments</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>You are given two&nbsp;<strong>0-indexed</strong>&nbsp;strings&nbsp;<code>str1</code>&nbsp;and&nbsp;<code>str2</code>.</p>



<p>In an operation, you select a&nbsp;<strong>set</strong>&nbsp;of indices in&nbsp;<code>str1</code>, and for each index&nbsp;<code>i</code>&nbsp;in the set, increment&nbsp;<code>str1[i]</code>&nbsp;to the next character&nbsp;<strong>cyclically</strong>. That is&nbsp;<code>'a'</code>&nbsp;becomes&nbsp;<code>'b'</code>,&nbsp;<code>'b'</code>&nbsp;becomes&nbsp;<code>'c'</code>, and so on, and&nbsp;<code>'z'</code>&nbsp;becomes&nbsp;<code>'a'</code>.</p>



<p>Return&nbsp;<code>true</code>&nbsp;<em>if it is possible to make&nbsp;</em><code>str2</code>&nbsp;<em>a subsequence of&nbsp;</em><code>str1</code>&nbsp;<em>by performing the operation&nbsp;<strong>at most once</strong></em>,&nbsp;<em>and</em>&nbsp;<code>false</code>&nbsp;<em>otherwise</em>.</p>



<p><strong>Note:</strong>&nbsp;A subsequence of a string is a new string that is formed from the original string by deleting some (possibly none) of the characters without disturbing the relative positions of the remaining characters.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> str1 = "abc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select index 2 in str1.
Increment str1[2] to become 'd'. 
Hence, str1 becomes "abd" and str2 is now a subsequence. Therefore, true is returned.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> str1 = "zc", str2 = "ad"
<strong>Output:</strong> true
<strong>Explanation:</strong> Select indices 0 and 1 in str1. 
Increment str1[0] to become 'a'. 
Increment str1[1] to become 'd'. 
Hence, str1 becomes "ad" and str2 is now a subsequence. Therefore, true is returned.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> str1 = "ab", str2 = "d"
<strong>Output:</strong> false
<strong>Explanation:</strong> In this example, it can be shown that it is impossible to make str2 a subsequence of str1 using the operation at most once. 
Therefore, false is returned.</pre>



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



<ul><li><code>1 &lt;= str1.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= str2.length &lt;= 10<sup>5</sup></code></li><li><code>str1</code>&nbsp;and&nbsp;<code>str2</code>&nbsp;consist of only lowercase English letters.</li></ul>



<h2><strong>Solution: Two pointers</strong></h2>



<p>s1[i] and s2[j] can match if <br>s1[i] == s2[j] or inc(s1[i]) == s2[j]</p>



<p>If matched: ++i; ++j else ++i.</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">class Solution {
public:
  bool canMakeSubsequence(string_view s1, string_view s2) {    
    for (int i = 0, j = 0, n = s1.size(), m = s2.size(); i &lt; n; ++i)
      if (s1[i] == s2[j] || (s1[i] - 'a' + 1) % 26 == s2[j] - 'a')
        if (++j == m) return true;
    return false;
  }
};</pre>
</div></div>



<p>Iterator version</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  bool canMakeSubsequence(string_view s1, string_view s2) {    
    for (auto i = begin(s1), j = begin(s2); i != end(s1); ++i)
      if (*i == *j || (*i - 'a' + 1) % 26 == *j - 'a')
        if (++j == end(s2)) return true;
    return false;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/">花花酱 LeetCode 2825. Make String a Subsequence Using Cyclic Increments</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/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 06:28:26 +0000</pubDate>
				<category><![CDATA[String]]></category>
		<category><![CDATA[bitset]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9293</guid>

					<description><![CDATA[<p>Given a string&#160;s, return&#160;the number of&#160;unique palindromes of length three&#160;that are a&#160;subsequence&#160;of&#160;s. Note that even if there are multiple ways to obtain the same subsequence,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/">花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</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>Given a string&nbsp;<code>s</code>, return&nbsp;<em>the number of&nbsp;<strong>unique palindromes of length three</strong>&nbsp;that are a&nbsp;<strong>subsequence</strong>&nbsp;of&nbsp;</em><code>s</code>.</p>



<p>Note that even if there are multiple ways to obtain the same subsequence, it is still only counted&nbsp;<strong>once</strong>.</p>



<p>A&nbsp;<strong>palindrome</strong>&nbsp;is a string that reads the same forwards and backwards.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>



<ul><li>For example,&nbsp;<code>"ace"</code>&nbsp;is a subsequence of&nbsp;<code>"<u>a</u>b<u>c</u>d<u>e</u>"</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aabca"
<strong>Output:</strong> 3
<strong>Explanation:</strong> The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "adc"
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no palindromic subsequences of length 3 in "adc".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "bbcbaba"
<strong>Output:</strong> 4
<strong>Explanation:</strong> The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
</pre>



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



<ul><li><code>3 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;consists of only lowercase English letters.</li></ul>



<h2><strong>Solution: Enumerate first <meta charset="utf-8">character of a palindrome</strong></h2>



<p>For a length 3 palindrome, we just need to enumerate the first character c.<br>We found the first and last occurrence of c in original string and scan the middle part to see how many unique characters there.<br><br>e.g. <meta charset="utf-8">aabca<br>Enumerate from a to z, looking for a*a, b*b, &#8230;, z*z.<br>For a*a, <meta charset="utf-8"><span style="text-decoration: underline;"><strong><span class="has-inline-color has-vivid-cyan-blue-color">a</span></strong></span><span class="has-inline-color has-vivid-red-color"><strong>abc</strong></span><span style="text-decoration: underline;"><span class="has-inline-color has-vivid-cyan-blue-color"><strong>a</strong></span></span>, we found first and last a, in between is <meta charset="utf-8"><span class="has-inline-color has-vivid-red-color"><strong>abc</strong></span>, which has 3 unique letters. <br>We can use a hastable or a bitset to track unique letters.</p>



<p>Time complexity: O(26*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 countPalindromicSubsequence(string s) {
    auto count = [&amp;](char c) -&gt; int {
      int l = s.find_first_of(c);
      int r = s.find_last_of(c);
      if (l == string::npos || r == string::npos) return 0;
      bitset&lt;26&gt; m;
      for (int i = l + 1; i &lt; r; ++i)
        m.set(s[i] - 'a');
      return m.count();
    };
    int ans = 0;
    for (char c = 'a'; c &lt;= 'z'; ++c)
      ans += count(c);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/string/leetcode-1930-unique-length-3-palindromic-subsequences/">花花酱 LeetCode 1930. Unique Length-3 Palindromic Subsequences</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/string/leetcode-1930-unique-length-3-palindromic-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1898. Maximum Number of Removable Characters</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 12 Aug 2021 02:40:40 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subsequence]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8567</guid>

					<description><![CDATA[<p>You are given two strings&#160;s&#160;and&#160;p&#160;where&#160;p&#160;is a&#160;subsequence&#160;of&#160;s. You are also given a&#160;distinct 0-indexed&#160;integer array&#160;removable&#160;containing a subset of indices of&#160;s&#160;(s&#160;is also&#160;0-indexed). You want to choose an integer&#160;k&#160;(0&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/">花花酱 LeetCode 1898. Maximum Number of Removable Characters</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>You are given two strings&nbsp;<code>s</code>&nbsp;and&nbsp;<code>p</code>&nbsp;where&nbsp;<code>p</code>&nbsp;is a&nbsp;<strong>subsequence&nbsp;</strong>of&nbsp;<code>s</code>. You are also given a&nbsp;<strong>distinct 0-indexed&nbsp;</strong>integer array&nbsp;<code>removable</code>&nbsp;containing a subset of indices of&nbsp;<code>s</code>&nbsp;(<code>s</code>&nbsp;is also&nbsp;<strong>0-indexed</strong>).</p>



<p>You want to choose an integer&nbsp;<code>k</code>&nbsp;(<code>0 &lt;= k &lt;= removable.length</code>) such that, after removing&nbsp;<code>k</code>&nbsp;characters from&nbsp;<code>s</code>&nbsp;using the&nbsp;<strong>first</strong>&nbsp;<code>k</code>&nbsp;indices in&nbsp;<code>removable</code>,&nbsp;<code>p</code>&nbsp;is still a&nbsp;<strong>subsequence</strong>&nbsp;of&nbsp;<code>s</code>. More formally, you will mark the character at&nbsp;<code>s[removable[i]]</code>&nbsp;for each&nbsp;<code>0 &lt;= i &lt; k</code>, then remove all marked characters and check if&nbsp;<code>p</code>&nbsp;is still a subsequence.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;</em><code>k</code><em>&nbsp;you can choose such that&nbsp;</em><code>p</code><em>&nbsp;is still a&nbsp;<strong>subsequence</strong>&nbsp;of&nbsp;</em><code>s</code><em>&nbsp;after the removals</em>.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcacb", p = "ab", removable = [3,1,0]
<strong>Output:</strong> 2
<strong>Explanation</strong>: After removing the characters at indices 3 and 1, "a<s><strong>b</strong></s>c<s><strong>a</strong></s>cb" becomes "accb".
"ab" is a subsequence of "<strong><u>a</u></strong>cc<strong><u>b</u></strong>".
If we remove the characters at indices 3, 1, and 0, "<s><strong>ab</strong></s>c<s><strong>a</strong></s>cb" becomes "ccb", and "ab" is no longer a subsequence.
Hence, the maximum k is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcbddddd", p = "abcd", removable = [3,2,1,4,5,6]
<strong>Output:</strong> 1
<strong>Explanation</strong>: After removing the character at index 3, "abc<s><strong>b</strong></s>ddddd" becomes "abcddddd".
"abcd" is a subsequence of "<strong>abcd</strong>dddd".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abcab", p = "abc", removable = [0,1,2,3,4]
<strong>Output:</strong> 0
<strong>Explanation</strong>: If you remove the first index in the array removable, "abc" is no longer a subsequence.
</pre>



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



<ul><li><code>1 &lt;= p.length &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= removable.length &lt; s.length</code></li><li><code>0 &lt;= removable[i] &lt; s.length</code></li><li><code>p</code>&nbsp;is a&nbsp;<strong>subsequence</strong>&nbsp;of&nbsp;<code>s</code>.</li><li><code>s</code>&nbsp;and&nbsp;<code>p</code>&nbsp;both consist of lowercase English letters.</li><li>The elements in&nbsp;<code>removable</code>&nbsp;are&nbsp;<strong>distinct</strong>.</li></ul>



<h2><strong>Solution: Binary Search + Two Pointers</strong></h2>



<p>If we don&#8217;t remove any thing, p is a subseq of s, as we keep removing, at some point L, p is no longer a subseq of s. e.g [0:True, 1: True, &#8230;, L &#8211; 1: True, L: False, L+1: False, &#8230;, m:False], this array is monotonic. We can use binary search to find the smallest L such that p is no long a subseq of s. Ans = L &#8211; 1.</p>



<p>For each guess, we can use two pointers to check whether p is subseq of removed(s) in O(n).</p>



<p>Time complexity: O(nlogn)<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 maximumRemovals(string s, string p, vector&lt;int&gt;&amp; removable) {
    const int n = s.length();
    const int t = p.length();
    const int m = removable.size();    
    int l = 0;
    int r = m + 1;
    vector&lt;int&gt; idx(n, INT_MAX);
    for (int i = 0; i &lt; m; ++i)
      idx[removable[i]] = i;
    while (l &lt; r) {
      int mid = l + (r - l) / 2;
      int j = 0;
      for (int i = 0; i &lt; n &amp;&amp; j &lt; t; ++i)
        if (idx[i] &gt;= mid &amp;&amp; s[i] == p[j]) ++j;      
      if (j != t)
        r = mid;
      else
        l = mid + 1;
    }
    // l is the smallest number s.t. p is no longer a subseq of s.
    return l - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/">花花酱 LeetCode 1898. Maximum Number of Removable Characters</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/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1771. Maximize Palindrome Length From Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1771-maximize-palindrome-length-from-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1771-maximize-palindrome-length-from-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Feb 2021 08:45:45 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8152</guid>

					<description><![CDATA[<p>You are given two strings,&#160;word1&#160;and&#160;word2. You want to construct a string in the following manner: Choose some&#160;non-empty&#160;subsequence&#160;subsequence1&#160;from&#160;word1. Choose some&#160;non-empty&#160;subsequence&#160;subsequence2&#160;from&#160;word2. Concatenate the subsequences:&#160;subsequence1 + subsequence2, to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1771-maximize-palindrome-length-from-subsequences/">花花酱 LeetCode 1771. Maximize Palindrome Length From Subsequences</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 is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1771. Maximize Palindrome Length From Subsequences - 刷题找工作 EP386" width="500" height="281" src="https://www.youtube.com/embed/0dbo8C64UFk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given two strings,&nbsp;<code>word1</code>&nbsp;and&nbsp;<code>word2</code>. You want to construct a string in the following manner:</p>



<ul><li>Choose some&nbsp;<strong>non-empty</strong>&nbsp;subsequence&nbsp;<code>subsequence1</code>&nbsp;from&nbsp;<code>word1</code>.</li><li>Choose some&nbsp;<strong>non-empty</strong>&nbsp;subsequence&nbsp;<code>subsequence2</code>&nbsp;from&nbsp;<code>word2</code>.</li><li>Concatenate the subsequences:&nbsp;<code>subsequence1 + subsequence2</code>, to make the string.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>length</strong>&nbsp;of the longest&nbsp;<strong>palindrome</strong>&nbsp;that can be constructed in the described manner.&nbsp;</em>If no palindromes can be constructed, return&nbsp;<code>0</code>.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;of a string&nbsp;<code>s</code>&nbsp;is a string that can be made by deleting some (possibly none) characters from&nbsp;<code>s</code>&nbsp;without changing the order of the remaining characters.</p>



<p>A&nbsp;<strong>palindrome</strong>&nbsp;is a string that reads the same forward&nbsp;as well as backward.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word1 = "cacb", word2 = "cbba"
<strong>Output:</strong> 5
<strong>Explanation:</strong> Choose "ab" from word1 and "cba" from word2 to make "abcba", which is a palindrome.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word1 = "ab", word2 = "ab"
<strong>Output:</strong> 3
<strong>Explanation:</strong> Choose "ab" from word1 and "a" from word2 to make "aba", which is a palindrome.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word1 = "aa", word2 = "bb"
<strong>Output:</strong> 0
<strong>Explanation:</strong> You cannot construct a palindrome from the described method, so return 0.</pre>



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



<ul><li><code>1 &lt;= word1.length, word2.length &lt;= 1000</code></li><li><code>word1</code>&nbsp;and&nbsp;<code>word2</code>&nbsp;consist of lowercase English letters.</li></ul>



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



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386.png" alt="" class="wp-image-8182" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-2.png" alt="" class="wp-image-8183" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/02/1771-ep386-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Similar to <a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-516-longest-palindromic-subsequence/" data-type="post" data-id="2860">花花酱 LeetCode 516. Longest Palindromic Subsequence</a></p>



<p>Let s = word1 + word2, build dp table on s. We just need to make sure there&#8217;s at least one char from each  string.</p>



<p>Time complexity: O((m+n)^2)<br>Space complexity: O((m+n)^2)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestPalindrome(string word1, string word2) {
    const int l1 = word1.length();
    const int l2 = word2.length();
    string s = word1 + word2;
    const int n = l1 + l2;
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n));
    for (int i = 0; i &lt; n; ++i) dp[i][i] = 1;
    for (int l = 2; l &lt;= n; ++l)
      for (int i = 0, j = i + l - 1; j &lt; n; ++i, ++j) {
        if (s[i] == s[j])
          dp[i][j] = dp[i + 1][j - 1] + 2;
        else
          dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
      }
    
    int ans = 0;
    for (int i = 0; i &lt; l1; ++i)
      for (int j = 0; j &lt; l2; ++j)
        if (word1[i] == word2[j])
          ans = max(ans, dp[i][l1 + j]);
    return ans;
  }
};</pre>
</div></div>



<p>O(m+n) Space complexity</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestPalindrome(string word1, string word2) {
    const int l1 = word1.length();
    const int l2 = word2.length();
    string s = word1 + word2;
    const int n = l1 + l2;
    vector&lt;int&gt; dp1(n, 1), dp2(n);
    int ans = 0;
    for (int l = 2; l &lt;= n; ++l) {
      vector&lt;int&gt; dp(n);
      for (int i = 0, j = i + l - 1; j &lt; n; ++i, ++j) {
        if (s[i] == s[j]) {
          dp[i] = dp2[i + 1] + 2;
          if (i &lt; l1 &amp;&amp; j &gt;= l1)
            ans = max(ans, dp[i]);
        } else {
          dp[i] = max(dp1[i + 1], dp1[i]);
        }
      }
      // dp2, dp1 = dp1, dp
      dp1.swap(dp); 
      dp2.swap(dp);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1771-maximize-palindrome-length-from-subsequences/">花花酱 LeetCode 1771. Maximize Palindrome Length From Subsequences</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-1771-maximize-palindrome-length-from-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1458. Max Dot Product of Two Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1458-max-dot-product-of-two-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1458-max-dot-product-of-two-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 24 May 2020 19:59:09 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6825</guid>

					<description><![CDATA[<p>Given two arrays&#160;nums1&#160;and&#160;nums2. Return the maximum dot product&#160;between&#160;non-empty&#160;subsequences of nums1 and nums2 with the same length. A subsequence of a array is a new array&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1458-max-dot-product-of-two-subsequences/">花花酱 LeetCode 1458. Max Dot Product of Two Subsequences</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-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1458. Max Dot Product of Two Subsequences - 刷题找工作 EP330" width="500" height="375" src="https://www.youtube.com/embed/Zj871uqXadE?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given two arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>.</p>



<p>Return the maximum dot product&nbsp;between&nbsp;<strong>non-empty</strong>&nbsp;subsequences of nums1 and nums2 with the same length.</p>



<p>A subsequence of a array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie,&nbsp;<code>[2,3,5]</code>&nbsp;is a subsequence of&nbsp;<code>[1,2,3,4,5]</code>&nbsp;while&nbsp;<code>[1,5,3]</code>&nbsp;is not).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [2,1,-2,5], nums2 = [3,0,-6]
<strong>Output:</strong> 18
<strong>Explanation:</strong> Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2.
Their dot product is (2*3 + (-2)*(-6)) = 18.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [3,-2], nums2 = [2,-6,7]
<strong>Output:</strong> 21
<strong>Explanation:</strong> Take subsequence [3] from nums1 and subsequence [7] from nums2.
Their dot product is (3*7) = 21.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [-1,-1], nums2 = [1,1]
<strong>Output:</strong> -1
<strong>Explanation: </strong>Take subsequence [-1] from nums1 and subsequence [1] from nums2.
Their dot product is -1.</pre>



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



<ul><li><code>1 &lt;= nums1.length, nums2.length &lt;= 500</code></li><li><code>-1000 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li></ul>



<h2><strong>Solution: 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/05/1458-ep330.png" alt="" class="wp-image-6828" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1458-ep330.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1458-ep330-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/05/1458-ep330-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i][j] := max product of nums1[0~i], nums2[0~j].</p>



<p>dp[i][j] = max(dp[i-1][j], dp[i][j -1], max(0, dp[i-1][j-1]) + nums1[i]*nums2[j])</p>



<p>Time complexity: O(n1*n2)<br>Space complexity: O(n1*n2)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxDotProduct(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    const int n1 = nums1.size();
    const int n2 = nums2.size();
    // dp[i][j] = max dot product of two subsequences 
    // of nums1[0:i] and nums2[0:j]
    vector&lt;vector&lt;int&gt;&gt; dp(n1 + 1, vector&lt;int&gt;(n2 + 1, INT_MIN / 2));
        
    for (int i = 1; i &lt;= n1; ++i)
      for (int j = 1; j &lt;= n2; ++j)
        dp[i][j] = max({
          dp[i - 1][j],
          dp[i][j - 1],
          max(0, dp[i - 1][j - 1]) + nums1[i - 1] * nums2[j - 1]
        });
    return dp[n1][n2];
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxDotProduct(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    const int n1 = nums1.size();
    const int n2 = nums2.size();
    // dp[i][j] = max dot product of two subsequences 
    // of nums1[0~i] and nums2[0~j]
    vector&lt;vector&lt;int&gt;&gt; dp(n1, vector&lt;int&gt;(n2));
        
    for (int i = 0; i &lt; n1; ++i)
      for (int j = 0; j &lt; n2; ++j) {
        dp[i][j] = nums1[i] * nums2[j];
        if (i &gt; 0 &amp;&amp; j &gt; 0) dp[i][j] += max(0, dp[i - 1][j - 1]);
        if (i &gt; 0) dp[i][j] = max(dp[i][j], dp[i - 1][j]);
        if (j &gt; 0) dp[i][j] = max(dp[i][j], dp[i][j - 1]);     
      }
    return dp.back().back();
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1458-max-dot-product-of-two-subsequences/">花花酱 LeetCode 1458. Max Dot Product of Two Subsequences</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-1458-max-dot-product-of-two-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1332. Remove Palindromic Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1332-remove-palindromic-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1332-remove-palindromic-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Jan 2020 18:11:49 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6142</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;consisting only of&#160;letters&#160;'a'&#160;and&#160;'b'. In a single step you can remove one&#160;palindromic&#160;subsequence&#160;from&#160;s. Return the minimum number of steps to make the given string empty.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1332-remove-palindromic-subsequences/">花花酱 LeetCode 1332. Remove Palindromic Subsequences</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>Given a string&nbsp;<code>s</code>&nbsp;consisting only of&nbsp;letters&nbsp;<code>'a'</code>&nbsp;and&nbsp;<code>'b'</code>. In a single step you can remove one&nbsp;palindromic&nbsp;<strong>subsequence</strong>&nbsp;from&nbsp;<code>s</code>.</p>



<p>Return the minimum number of steps to make the given string empty.</p>



<p>A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.</p>



<p>A string is called palindrome if is one that reads the same backward as well as forward.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ababa"
<strong>Output:</strong> 1
<strong>Explanation:</strong> String is already palindrome
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> "<strong>a</strong>bb" -&gt; "<strong>bb</strong>" -&gt; "". 
Remove palindromic subsequence "a" then "bb".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "baabb"
<strong>Output:</strong> 2
<strong>Explanation:</strong> "<strong>baa</strong>b<strong>b</strong>" -&gt; "b" -&gt; "". 
Remove palindromic subsequence "baab" then "b".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = ""
<strong>Output:</strong> 0
</pre>



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



<ul><li><code>0 &lt;= s.length &lt;= 1000</code></li><li><code>s</code>&nbsp;only consists of letters &#8216;a&#8217; and &#8216;b&#8217;</li></ul>



<h2><strong>Solution: Math</strong></h2>



<p>if s is empty => 0 step<br>if s is a palindrome => 1 step<br>Otherwise, 2 steps&#8230;<br>1. delete all the as<br>2. delete all the bs</p>



<p>Time complexity: O(n)<br>Space complexity: O(n) / 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 removePalindromeSub(string s) {
    if (s.empty()) return 0;
    if (s == string(rbegin(s), rend(s))) return 1;
    return 2;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1332-remove-palindromic-subsequences/">花花酱 LeetCode 1332. Remove Palindromic Subsequences</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/math/leetcode-1332-remove-palindromic-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1218. Longest Arithmetic Subsequence of Given Difference</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1218-longest-arithmetic-subsequence-of-given-difference/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1218-longest-arithmetic-subsequence-of-given-difference/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Oct 2019 04:30:42 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5715</guid>

					<description><![CDATA[<p>Given an integer array&#160;arr&#160;and an integer&#160;difference, return the length of the longest subsequence in&#160;arr&#160;which is an arithmetic sequence such that the difference between adjacent elements&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1218-longest-arithmetic-subsequence-of-given-difference/">花花酱 LeetCode 1218. Longest Arithmetic Subsequence of Given Difference</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-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1218. Longest Arithmetic Subsequence of Given Difference - 刷题找工作 EP273" width="500" height="375" src="https://www.youtube.com/embed/1THU4Aa9akQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an integer array&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>difference</code>, return the length of the longest subsequence in&nbsp;<code>arr</code>&nbsp;which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals&nbsp;<code>difference</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,4], difference = 1
<strong>Output:</strong> 4
<strong>Explanation: </strong>The longest arithmetic subsequence is [1,2,3,4].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,3,5,7], difference = 1
<strong>Output:</strong> 1
<strong>Explanation: </strong>The longest arithmetic subsequence is any single element.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,5,7,8,5,3,4,2,1], difference = -2
<strong>Output:</strong> 4
<strong>Explanation: </strong>The longest arithmetic subsequence is [7,5,3,1].
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;= 10^5</code></li><li><code>-10^4 &lt;= arr[i], difference &lt;= 10^4</code></li></ul>



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



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/10/1218-ep273.png" alt="" class="wp-image-5729" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/10/1218-ep273.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/10/1218-ep273-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/10/1218-ep273-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>dp[i] := max length of sequence ends with x<br>dp[x] = max(0, dp[x &#8211; diff]) + 1</p>



<p>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 longestSubsequence(vector&lt;int&gt;&amp; arr, int d) {
    unordered_map&lt;int, int&gt; dp;
    int ans = 0;
    for (int x : arr)      
      ans = max(ans, dp[x] = dp[x - d] + 1);    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1218-longest-arithmetic-subsequence-of-given-difference/">花花酱 LeetCode 1218. Longest Arithmetic Subsequence of Given Difference</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-1218-longest-arithmetic-subsequence-of-given-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1092. Shortest Common Supersequence</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1092-shortest-common-supersequence/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1092-shortest-common-supersequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 16 Jun 2019 07:59:27 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[LCS]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5229</guid>

					<description><![CDATA[<p>Given two strings&#160;str1&#160;and&#160;str2,&#160;return the shortest string that has both&#160;str1&#160;and&#160;str2&#160;as subsequences.&#160;&#160;If multiple answers exist, you may return any of them. (A string S is a subsequence&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1092-shortest-common-supersequence/">花花酱 LeetCode 1092. Shortest Common Supersequence</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-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/rfV2BJp8YA8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given two strings&nbsp;<code>str1</code>&nbsp;and&nbsp;<code>str2</code>,&nbsp;return the shortest string that has both&nbsp;<code>str1</code>&nbsp;and&nbsp;<code>str2</code>&nbsp;as subsequences.&nbsp;&nbsp;If multiple answers exist, you may return any of them.</p>



<p><em>(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen&nbsp;anywherefrom T) results in the string S.)</em></p>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input: </strong>str1 = "abac", str2 = "cab"
<strong>Output: </strong>"cabac"
<strong>Explanation: </strong>
str1 = "abac" is a substring of "cabac" because we can delete the first "c".
str2 = "cab" is a substring of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
</pre>



<p><strong>Note:</strong></p>



<ol><li><code>1 &lt;= str1.length, str2.length &lt;= 1000</code></li><li><code>str1</code>&nbsp;and&nbsp;<code>str2</code>&nbsp;consist of lowercase English letters.</li></ol>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/1092-ep251.png" alt="" class="wp-image-5232" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/1092-ep251.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/1092-ep251-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/06/1092-ep251-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<h2><strong>Solution: LCS </strong></h2>



<p>Find the LCS (longest common sub-sequence) of two strings, and insert unmatched characters into the LCS.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 16 ms, 15.3 MB
class Solution {
public:
  string shortestCommonSupersequence(string str1, string str2) {
    int l1 = str1.length();
    int l2 = str2.length();    
    vector&lt;vector&lt;int&gt;&gt; dp(l1 + 1, vector&lt;int&gt;(l2 + 1));    
    for (int i = 1; i &lt;= l1; ++i)
      for (int j = 1; j &lt;= l2; ++j)
        dp[i][j] = str1[i - 1] == str2[j - 1] ? 
                     1 + dp[i - 1][j - 1] : 
                     max(dp[i - 1][j], dp[i][j - 1]);
    deque&lt;char&gt; ans;
    while (l1 || l2) {
      char c;
      if (l1 == 0) c = str2[--l2];
      else if (l2 == 0) c = str1[--l1];
      else if (str1[l1 - 1] == str2[l2 - 1]) c = str1[--l1] = str2[--l2];
      else if (dp[l1 - 1][l2] == dp[l1][l2]) c = str1[--l1];
      else if (dp[l1][l2 - 1] == dp[l1][l2]) c = str2[--l2];
      ans.push_front(c);
    }    
    return {begin(ans), end(ans)};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1092-shortest-common-supersequence/">花花酱 LeetCode 1092. Shortest Common Supersequence</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-1092-shortest-common-supersequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 960. Delete Columns to Make Sorted III</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-960-delete-columns-to-make-sorted-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-960-delete-columns-to-make-sorted-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 20 Dec 2018 05:49:15 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[increasing]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4505</guid>

					<description><![CDATA[<p>We are given an array&#160;A&#160;of&#160;N&#160;lowercase letter strings, all of the same length. Now, we may choose any set of deletion indices, and for each string,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-960-delete-columns-to-make-sorted-iii/">花花酱 LeetCode 960. Delete Columns to Make Sorted III</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>We are given an array&nbsp;<code>A</code>&nbsp;of&nbsp;<code>N</code>&nbsp;lowercase letter strings, all of the same length.</p>



<p>Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.</p>



<p>For example, if we have an array&nbsp;<code>A = ["babca","bbazb"]</code>&nbsp;and deletion indices&nbsp;<code>{0, 1, 4}</code>, then the final array after deletions is&nbsp;<code>["bc","az"]</code>.</p>



<p>Suppose we chose a set of deletion indices&nbsp;<code>D</code>&nbsp;such that after deletions, the final array has&nbsp;<strong>every element (row) in&nbsp;lexicographic</strong>&nbsp;order.</p>



<p>For clarity,&nbsp;<code>A[0]</code>&nbsp;is in lexicographic order (ie.&nbsp;<code>A[0][0] &lt;= A[0][1] &lt;= ... &lt;= A[0][A[0].length - 1]</code>),&nbsp;<code>A[1]</code>&nbsp;is in lexicographic order (ie.&nbsp;<code>A[1][0] &lt;= A[1][1] &lt;= ... &lt;= A[1][A[1].length - 1]</code>), and so on.</p>



<p>Return the minimum possible value of&nbsp;<code>D.length</code>.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>["babca","bbazb"]
<strong>Output: </strong>3
<strong>Explanation: </strong>After deleting columns 0, 1, and 4, the final array is A = ["bc", "az"].
Both these rows are individually in lexicographic order (ie. A[0][0] &lt;= A[0][1] and A[1][0] &lt;= A[1][1]).
Note that A[0] &gt; A[1] - the array A isn't necessarily in lexicographic order.
</pre>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>["edcba"]
<strong>Output: </strong>4
<strong>Explanation: </strong>If we delete less than 4 columns, the only row won't be lexicographically sorted.
</pre>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>["ghi","def","abc"]
<strong>Output: </strong>0
<strong>Explanation: </strong>All rows are already lexicographically sorted.
</pre>



<p><strong>Note:</strong></p>



<ol><li><code>1 &lt;= A.length &lt;= 100</code></li><li><code>1 &lt;= A[i].length &lt;= 100</code></li></ol>



<h1><strong>Solution: DP</strong></h1>



<p>dp[i] := max length of increasing sub-sequence (of all strings) ends with i-th letter.<br>dp[i] = max(dp[j] + 1) if all A[*][j] &lt;= A[*][i], j &lt; i<br>Time complexity: (n*L^2)<br>Space complexity: O(L)</p>



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


<pre class="crayon-plain-tag">// Author: Huahua, running time: 24 ms
class Solution {
public:
  int minDeletionSize(vector&lt;string&gt;&amp; A) {
    vector&lt;int&gt; dp(A[0].length(), 1);
    for (int i = 0; i &lt; A[0].length(); ++i)
      for (int j = 0; j &lt; i; ++j) {
        bool valid = true;
        for (const auto&amp; a : A)
          if (a[j] &gt; a[i]) {
            valid = false;
            break;
          }
        if (valid) dp[i] = max(dp[i], dp[j] + 1);
      }
    return A[0].length() - *max_element(begin(dp), end(dp));
  }
};</pre>


</div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, running time: 176 ms
class Solution:
  def minDeletionSize(self, A):
    n = len(A[0])
    dp = [1] * n
    for i in range(1, n):
      for j in range(i):
        valid = True
        for a in A:
          if a[j] &gt; a[i]: 
            valid = False
            break
        if valid:
          dp[i] = max(dp[i], dp[j] + 1)
    return n - max(dp)</pre>

</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-960-delete-columns-to-make-sorted-iii/">花花酱 LeetCode 960. Delete Columns to Make Sorted III</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-960-delete-columns-to-make-sorted-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 940. Distinct Subsequences II</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-940-distinct-subsequences-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-940-distinct-subsequences-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 14 Nov 2018 09:04:29 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4309</guid>

					<description><![CDATA[<p>Problem Given a string S, count the number of distinct, non-empty subsequences of S . Since the result may be large, return the answer modulo 10^9 + 7. Example 1:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-940-distinct-subsequences-ii/">花花酱 LeetCode 940. Distinct Subsequences 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[<h1><strong>Problem</strong></h1>
<p>Given a string <code>S</code>, count the number of distinct, non-empty subsequences of <code>S</code> .</p>
<p>Since the result may be large, <strong>return the answer modulo <code>10^9 + 7</code></strong>.</p>
<p><strong>Example 1:</strong></p>
<pre class="&quot;crayon:false”"><strong>Input: </strong><span id="example-input-1-1">"abc"</span>
<strong>Output: </strong><span id="example-output-1">7</span>
<strong>Explanation</strong>: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".
</pre>
<p><strong>Example 2:</strong></p>
<pre class="&quot;crayon:false”"><strong>Input: </strong><span id="example-input-2-1">"aba"</span>
<strong>Output: </strong><span id="example-output-2">6
</span><strong>Explanation</strong>: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba".
</pre>
<p><strong>Example 3:</strong></p>
<pre class="&quot;crayon:false”"><strong>Input: </strong><span id="example-input-3-1">"aaa"</span>
<strong>Output: </strong><span id="example-output-3">3
</span><strong>Explanation</strong>: The 3 distinct subsequences are "a", "aa" and "aaa".</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>S</code> contains only lowercase letters.</li>
<li><code>1 &lt;= S.length &lt;= 2000</code></li>
</ol>
<h1><strong>Solution: DP</strong></h1>
<p class="">counts[i][j] := # of distinct sub sequences of s[1-&gt;i] and ends with letter j. (&#8216;a'&lt;= j &lt;= &#8216;z&#8217;)</p>
<p class="">Initialization:</p>
<p class="">counts[*][*] = 0</p>
<p class="">Transition:</p>
<p class="">counts[i][j] = sum(counts[i-1]) + 1 if s[i] == j  else counts[i-1][j]</p>
<p class="">ans = sum(counts[n])</p>
<p>e.g. S = &#8220;abc&#8221;</p>
<p>counts[1] = {&#8216;a&#8217; : 1}<br />
counts[2] = {&#8216;a&#8217; : 1, &#8216;b&#8217; : 1 + 1 = 2}<br />
counts[3] = {&#8216;a&#8217; : 1, &#8216;b&#8217; : 2, &#8216;c&#8217;: 1 + 2 + 1 = 4}<br />
ans = sum(counts[3]) = 1 + 2 + 4 = 7</p>
<p>Time complexity: O(N*26)</p>
<p>Space complexity: O(N*26) -&gt; O(26)</p>
<p><div class="responsive-tabs">
<h2 class="tabtitle">C++</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag">// Author: Huahua, running time: 12 ms
class Solution {
public:
  int distinctSubseqII(string S) {
    constexpr int kMod = 1e9 + 7;
    std::vector&lt;int&gt; counts(26);
    for (char c : S)
      counts[c - 'a'] = accumulate(begin(counts), end(counts), 1L) % kMod;
    return accumulate(begin(counts), end(counts), 0L) % kMod;
  }
};</pre><p></div><h2 class="tabtitle">Python3</h2>
<div class="tabcontent">
</p><pre class="crayon-plain-tag"># Author: Huahua, running time: 64 ms
class Solution:
  def distinctSubseqII(self, S):
    kMod = 10**9 + 7
    dp = {}
    for c in S:
      dp[c] = (sum(dp.values()) + 1) % kMod
    return sum(dp.values()) % kMod</pre><p></div></div></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-940-distinct-subsequences-ii/">花花酱 LeetCode 940. Distinct Subsequences 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-940-distinct-subsequences-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 891. Sum of Subsequence Widths</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-891-sum-of-subsequence-widths/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-891-sum-of-subsequence-widths/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 21 Aug 2018 00:31:45 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3640</guid>

					<description><![CDATA[<p>Problem Given an array of integers A, consider all non-empty subsequences of A. For any sequence S, let the width of S be the difference between the maximum and&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-891-sum-of-subsequence-widths/">花花酱 LeetCode 891. Sum of Subsequence Widths</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/lfF7XqwXokw?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given an array of integers <code>A</code>, consider all non-empty subsequences of <code>A</code>.</p>
<p>For any sequence S, let the <em>width</em> of S be the difference between the maximum and minimum element of S.</p>
<p>Return the sum of the widths of all subsequences of A.</p>
<p>As the answer may be very large, <strong>return the answer modulo 10^9 + 7</strong>.</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong><span id="example-input-1-1">[2,1,3]</span>
<strong>Output: </strong><span id="example-output-1">6</span>
<strong>Explanation:
</strong>Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.
</pre>
<p><strong>Note:</strong></p>
<ul>
<li><code>1 &lt;= A.length &lt;= 20000</code></li>
<li><code>1 &lt;= A[i] &lt;= 20000</code></li>
</ul>
<p><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></p>
<p><img class="alignnone size-full wp-image-3669" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/891-ep218.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/891-ep218.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/891-ep218-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/08/891-ep218-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<h1><strong>Solution: Math</strong></h1>
<p>Sort the array, for A[i]:</p>
<ul>
<li>i numbers &lt;= A[i]. A[i] is the upper bound of 2^i subsequences.</li>
<li>n &#8211; i &#8211; 1 numbers &gt;= A[i]. A[i] is the lower bound of 2^(n &#8211; i &#8211; 1) subsequences.</li>
<li>A[i] contributes A[i] * 2^i &#8211; A[i] * 2^(n &#8211; i &#8211; 1) to the ans.</li>
</ul>
<p>\(ans = \sum\limits_{i=0}^{n-1}A_{i}2^{i} &#8211; A_{i}2^{n &#8211; i &#8211; 1} =\sum\limits_{i=0}^{n-1}(A_i &#8211; A_{n-i-1})2^{i}\)</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 56 ms
class Solution {
public:
  int sumSubseqWidths(vector&lt;int&gt;&amp; A) {
    constexpr long kMod = 1e9 + 7;
    const int n = A.size();
    sort(begin(A), end(A));
    long ans = 0;
    long p = 1;
    for (int i = 0; i &lt; n; ++i) {
      ans = (ans + (A[i] - A[n - i - 1]) * p) % kMod;
      p = (p &lt;&lt; 1) % kMod;
    }
    return (ans + kMod) % kMod;
  }
};</pre><p>Time complexity: O(n)</p>
<p>Space complexity: O(n)</p>
<p>Counting sort</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 16 / 44 ms (beats 100%)
static auto x = [](){std::ios::sync_with_stdio(false);cin.tie(nullptr);return nullptr;}();

class Solution {
public:
  int sumSubseqWidths(vector&lt;int&gt;&amp; A) {
    constexpr long kMod = 1e9 + 7;
    const int n = A.size();    
    countingSort(A);
    long ans = 0;
    long p = 1;
    for (int i = 0; i &lt; n; ++i) {
      ans = (ans + (A[i] - A[n - i - 1]) * p) % kMod;
      p = (p &lt;&lt; 1) % kMod;
    }
    return (ans + kMod) % kMod;
  }
private:
  void countingSort(vector&lt;int&gt;&amp; A) {    
    int max_v = INT_MIN;
    int min_v = INT_MAX;
    for (int a : A) {      
      if (a &gt; max_v) max_v = a;
      if (a &lt; min_v) min_v = a;      
    }      
    vector&lt;int&gt; c(max_v - min_v + 1);
    for (int a : A)
      ++c[a - min_v];
    int i = 0;
    int j = 0;
    while (i &lt; c.size()) {
      if (--c[i] &gt;= 0) 
        A[j++] = i + min_v;
      else
        ++i;
    }
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-891-sum-of-subsequence-widths/">花花酱 LeetCode 891. Sum of Subsequence Widths</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/math/leetcode-891-sum-of-subsequence-widths/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 115. Distinct Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-115-distinct-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-115-distinct-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 20 Jul 2018 02:56:39 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[counting]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3226</guid>

					<description><![CDATA[<p>Problem Given a string S and a string T, count the number of distinct subsequences of S which equals T. A subsequence of a string is a new string which is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-115-distinct-subsequences/">花花酱 LeetCode 115. Distinct Subsequences</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/mPqqXh8XvWY?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given a string <strong>S</strong> and a string <strong>T</strong>, count the number of distinct subsequences of <strong>S</strong> which equals <strong>T</strong>.</p>
<p>A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, <code>"ACE"</code> is a subsequence of <code>"ABCDE"</code> while <code>"AEC"</code> is not).</p>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false "><strong>Input: </strong>S = "rabbbit", T = "rabbit"
<strong>Output:</strong> 3
<strong>Explanation: </strong> As shown below, there are 3 ways you can generate "rabbit" from S. (The caret symbol ^ means the chosen letters) 
rabbbit
^^^^ ^^
rabbbit
^^ ^^^^
rabbbit
^^^ ^^^</pre>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>S = "babgbag", T = "bag"
<strong>Output:</strong> 5
<strong>Explanation: </strong> As shown below, there are 5 ways you can generate "bag" from S. (The caret symbol ^ means the chosen letters)
babgbag
^^ ^
babgbag
^^ ^
babgbag
^ ^^
babgbag
^ ^^
babgbag
^^^</pre>
<h1><strong>Solution: DP</strong></h1>
<p><img class="alignnone size-full wp-image-3234" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/115-ep208.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/115-ep208.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/115-ep208-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/115-ep208-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p>Time complexity: O(|s| * |t|)</p>
<p>Space complexity: O(|s| * |t|)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int numDistinct(string s, string t) {
    int ls = s.length();
    int lt = t.length();
    vector&lt;vector&lt;int&gt;&gt; dp(lt + 1, vector&lt;int&gt;(ls + 1));
    fill(begin(dp[0]), end(dp[0]), 1);        
    for (int i = 1; i &lt;= lt; ++i)
      for (int j = 1; j &lt;= ls; ++j)
        dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);        
    return dp[lt][ls];
  }
};</pre><p></p>
<h1><strong>Related Problems:</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/">花花酱 LeetCode 72. Edit Distance</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-115-distinct-subsequences/">花花酱 LeetCode 115. Distinct Subsequences</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-115-distinct-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 491. Increasing Subsequences</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-491-increasing-subsequences/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-491-increasing-subsequences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 18 Jul 2018 04:19:36 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[increasing]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3207</guid>

					<description><![CDATA[<p>Problem Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-491-increasing-subsequences/">花花酱 LeetCode 491. Increasing Subsequences</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<div class="question-description__3U1T">
<div>
<h2><strong>Problem</strong></h2>
<p>Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2 .</p>
<p><b>Example:</b></p>
<pre class="crayon:false "><b>Input:</b> [4, 6, 7, 7]
<b>Output:</b> [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
</pre>
<p><b>Note:</b></p>
<ol>
<li>The length of the given array will not exceed 15.</li>
<li>The range of integer in the given array is [-100,100].</li>
<li>The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.</li>
</ol>
</div>
</div>
<h1><strong>Solution: DFS</strong></h1>
<p>Time complexity: O(2^n)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 140 ms (&lt;99.88%)
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; findSubsequences(vector&lt;int&gt;&amp; nums) {
    vector&lt;vector&lt;int&gt;&gt; ans;
    vector&lt;int&gt; cur;
    dfs(nums, 0, cur, ans);
    return ans;
  }
private:
  void dfs(const vector&lt;int&gt;&amp; nums, int s, vector&lt;int&gt;&amp; cur, vector&lt;vector&lt;int&gt;&gt;&amp; ans) {    
    unordered_set&lt;int&gt; seen;
    for (int i = s; i &lt; nums.size(); ++i) {
      if (!cur.empty() &amp;&amp; nums[i] &lt; cur.back()) continue;
      // each number can be used only once at the same depth.
      if (seen.count(nums[i])) continue; 
      seen.insert(nums[i]);
      cur.push_back(nums[i]);
      if (cur.size() &gt; 1) 
        ans.push_back(cur);
      dfs(nums, i + 1, cur, ans);
      cur.pop_back();
    }
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/searching/leetcode-491-increasing-subsequences/">花花酱 LeetCode 491. Increasing Subsequences</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-491-increasing-subsequences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 334. Increasing Triplet Subsequence</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-334-increasing-triplet-subsequence/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-334-increasing-triplet-subsequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 29 May 2018 00:09:10 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[increasing]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2868</guid>

					<description><![CDATA[<p>Problem 题目大意：判断一个数组中是否存在长度为3的单调递增子序列。 Formally the function should: Return true if there exists i, j, k  such that arr[i] &#60; arr[j] &#60; arr[k] given 0 ≤ i &#60; j &#60; k ≤ n-1 else return false. Your algorithm should run in&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-334-increasing-triplet-subsequence/">花花酱 LeetCode 334. Increasing Triplet 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>Problem</h1>
<p>题目大意：判断一个数组中是否存在长度为3的单调递增子序列。</p>
<p>Formally the function should:</p>
<blockquote><p>Return true if there exists <i>i, j, k </i><br />
such that <i>arr[i]</i> &lt; <i>arr[j]</i> &lt; <i>arr[k]</i> given 0 ≤ <i>i</i> &lt; <i>j</i> &lt; <i>k</i> ≤ <i>n</i>-1 else return false.</p></blockquote>
<p>Your algorithm should run in O(<i>n</i>) time complexity and O(<i>1</i>) space complexity.</p>
<p><b>Examples:</b><br />
Given <code>[1, 2, 3, 4, 5]</code>,<br />
return <code>true</code>.</p>
<p>Given <code>[5, 4, 3, 2, 1]</code>,<br />
return <code>false</code>.</p>
<p><b>Credits:</b><br />
Special thanks to <a href="https://leetcode.com/discuss/user/DjangoUnchained">@DjangoUnchained</a> for adding this problem and creating all test cases.</p>
<h1><img class="alignnone size-full wp-image-2871" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/334-ep193.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/334-ep193.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/334-ep193-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/334-ep193-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution: Greedy</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 7 ms
class Solution {
public:
  bool increasingTriplet(vector&lt;int&gt;&amp; nums) {
    int min1 = INT_MAX;
    int min2 = INT_MAX;
    for (int num : nums) {
      if (num &gt; min2) return true;
      else if (num &lt; min1) {
        min1 = num;
      } else if (num &gt; min1 &amp;&amp; num &lt; min2) {
        min2 = num;
      }
    }
    return false;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-334-increasing-triplet-subsequence/">花花酱 LeetCode 334. Increasing Triplet 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/greedy/leetcode-334-increasing-triplet-subsequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 516. Longest Palindromic Subsequence</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-516-longest-palindromic-subsequence/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-516-longest-palindromic-subsequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 28 May 2018 19:07:46 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[Palindrome]]></category>
		<category><![CDATA[subsequence]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2860</guid>

					<description><![CDATA[<p>Problem 题目大意：找出最长回文子序列的长度。 https://leetcode.com/problems/longest-palindromic-subsequence/description/ Given a string s, find the longest palindromic subsequence&#8217;s length in s. You may assume that the maximum length of s is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-516-longest-palindromic-subsequence/">花花酱 LeetCode 516. Longest Palindromic 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[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/OZX1nqaQ_9M?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>题目大意：找出最长回文子序列的长度。</p>
<p><a href="https://leetcode.com/problems/longest-palindromic-subsequence/description/">https://leetcode.com/problems/longest-palindromic-subsequence/description/</a></p>
<p>Given a string s, find the longest palindromic subsequence&#8217;s length in s. You may assume that the maximum length of s is 1000.</p>
<p><b>Example 1:</b><br />
Input:</p>
<pre class="crayon:false">"bbbab"
</pre>
<p>Output:</p>
<pre class="crayon:false">4
</pre>
<p>One possible longest palindromic subsequence is &#8220;bbbb&#8221;.</p>
<p><b>Example 2:</b><br />
Input:</p>
<pre class="crayon:false">"cbbd"
</pre>
<p>Output:</p>
<pre class="crayon:false">2
</pre>
<p>One possible longest palindromic subsequence is &#8220;bb&#8221;.</p>
<h1><img class="alignnone size-full wp-image-2866" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/516-ep192.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/516-ep192.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/516-ep192-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/05/516-ep192-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution: DP</strong></h1>
<p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n^2)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 102 ms
class Solution {
public:
  int longestPalindromeSubseq(string s) {
    const int n = s.length();
    vector&lt;vector&lt;int&gt;&gt; dp(n, vector&lt;int&gt;(n, 0));
    for (int l = 1; l &lt;= n; ++l)
      for (int i = 0; i &lt;= n - l; ++i) {
        int j = i + l - 1;
        if (i == j) {
          dp[i][j] = 1;
          continue;
        }
        dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
        if (s[i] == s[j])
          dp[i][j] = dp[i + 1][j - 1] + 2;
      }
    return dp[0][n - 1];
  }
};</pre><p>Time complexity: O(n^2)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms
class Solution {
public:
  int longestPalindromeSubseq(string s) {
    const int n = s.length();
    vector&lt;int&gt; dp0(n); // sols of len = l
    vector&lt;int&gt; dp1(n); // sols of len = l - 1
    vector&lt;int&gt; dp2(n); // sols of len = l - 2
    for (int l = 1; l &lt;= n; ++l) {    
      for (int i = 0; i &lt;= n - l; ++i) {
        int j = i + l - 1;
        if (i == j) {
          dp0[i] = 1;
          continue;
        }
        if (s[i] == s[j])
          dp0[i] = dp2[i + 1] + 2;
        else
          dp0[i] = max(dp1[i + 1], dp1[i]);
      }
      dp0.swap(dp1);
      dp2.swap(dp0);
    }
    return dp1[0];
  }
};</pre><p>Python3</p><pre class="crayon-plain-tag">"""
Author: Huahua
Running time: 1276 ms
"""
class Solution:
  def longestPalindromeSubseq(self, s):
    n = len(s)
    dp0 = [0] * n
    dp1 = [1] * n
    dp2 = [0] * n
    for l in range(2, n + 1):
      for i in range(0, n - l + 1):        
        j = i + l - 1
        if s[i] == s[j]:
          dp0[i] = dp2[i + 1] + 2
        else:
          dp0[i] = max(dp1[i + 1], dp1[i])      
      dp0, dp1, dp2 = dp2, dp0, dp1
    return dp1[0]</pre><p>C#</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 116 ms (beats 100%)
public class Solution {
  public int LongestPalindromeSubseq(string s) {
    var n = s.Length; 
    var dp0 = new int[n];
    var dp1 = new int[n];
    var dp2 = new int[n];
    
    for (var l = 1; l &lt;= n; ++l) {
      for (var i = 0; i &lt;= n - l; ++i) {
        int j = i + l - 1;
        if (i == j) {
          dp0[i] = 1;
          continue;
        }
        if (s[i] == s[j])
          dp0[i] = dp2[i + 1] + 2;
        else
          dp0[i] = Math.Max(dp1[i], dp1[i + 1]);
      }
      var tmp = dp2;
      dp2 = dp1;
      dp1 = dp0;
      dp0 = tmp;
    }
    return dp1[0];
  }
}</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-516-longest-palindromic-subsequence/">花花酱 LeetCode 516. Longest Palindromic 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/dynamic-programming/leetcode-516-longest-palindromic-subsequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
