<?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>non-overlapping Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/non-overlapping/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/non-overlapping/</link>
	<description></description>
	<lastBuildDate>Wed, 12 Aug 2020 05:22:12 +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>non-overlapping Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/non-overlapping/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Aug 2020 05:21:45 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[non-overlapping]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7239</guid>

					<description><![CDATA[<p>Given an array&#160;nums&#160;and an integer&#160;target. Return the maximum number of&#160;non-empty&#160;non-overlapping&#160;subarrays such that the sum of values in each subarray is equal to&#160;target. Example 1: Input:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/">花花酱 LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target</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 an array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>target</code>.</p>



<p>Return the maximum number of&nbsp;<strong>non-empty</strong>&nbsp;<strong>non-overlapping</strong>&nbsp;subarrays such that the sum of values in each subarray is equal to&nbsp;<code>target</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1,1,1], target = 2
<strong>Output:</strong> 2
<strong>Explanation: </strong>There are 2 non-overlapping subarrays [<strong>1,1</strong>,1,<strong>1,1</strong>] with sum equals to target(2).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,3,5,1,4,2,-9], target = 6
<strong>Output:</strong> 2
<strong>Explanation: </strong>There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-2,6,6,3,5,4,1,2,8], target = 10
<strong>Output:</strong> 3
</pre>



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



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



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



<ul><li><code>1 &lt;= nums.length &lt;=&nbsp;10^5</code></li><li><code>-10^4 &lt;= nums[i] &lt;=&nbsp;10^4</code></li><li><code>0 &lt;= target &lt;= 10^6</code></li></ul>



<h2><strong>Solution: Prefix Sum + DP</strong></h2>



<p>Use a hashmap index to record the last index when a given prefix sum occurs.<br>dp[i] := max # of non-overlapping subarrays of nums[0~i], nums[i] is not required to be included.<br>dp[i+1] = max(dp[i],  // skip nums[i]<br>                          dp[index[sum &#8211; target] + 1] + 1) // use nums[i] to form a new subarray<br>ans = dp[n]</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">class Solution {
public:
  int maxNonOverlapping(vector&lt;int&gt;&amp; nums, int target) {
    const int n = nums.size();
    vector&lt;int&gt; dp(n + 1, 0); // ans at nums[i];
    unordered_map&lt;int, int&gt; index; // {prefix sum -&gt; last_index}
    index[0] = -1;    
    int sum = 0;
    for (int i = 0; i &lt; n; ++i) {
      sum += nums[i];
      int t = sum - target;
      dp[i + 1] = dp[i]; 
      if (index.count(t))
        dp[i + 1] = max(dp[i + 1], dp[index[t] + 1] + 1);
      index[sum] = i;      
    }
    return dp[n];
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/">花花酱 LeetCode 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target</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-1546-maximum-number-of-non-overlapping-subarrays-with-sum-equals-target/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 19 Jul 2020 07:12:08 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[non-overlapping]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[substring]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7122</guid>

					<description><![CDATA[<p>Given a string&#160;s&#160;of lowercase letters, you need to find the maximum number of&#160;non-empty&#160;substrings of&#160;s&#160;that meet the following conditions: The substrings do not overlap, that is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/">花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</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 1520. Maximum Number of Non-Overlapping Substrings - 刷题找工作 EP344" width="500" height="281" src="https://www.youtube.com/embed/yAeI2uo3GP8?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>s</code>&nbsp;of lowercase letters, you need to find the maximum number of&nbsp;<strong>non-empty</strong>&nbsp;substrings of&nbsp;<code>s</code>&nbsp;that meet the following conditions:</p>



<ol><li>The substrings do not overlap, that is for any two substrings&nbsp;<code>s[i..j]</code>&nbsp;and&nbsp;<code>s[k..l]</code>, either&nbsp;<code>j &lt; k</code>&nbsp;or&nbsp;<code>i &gt; l</code>&nbsp;is true.</li><li>A substring that contains a certain character&nbsp;<code>c</code>&nbsp;must also contain all occurrences of&nbsp;<code>c</code>.</li></ol>



<p>Find&nbsp;<em>the maximum number of substrings that meet the above conditions</em>. If there are multiple solutions with the same number of substrings,&nbsp;<em>return the one with minimum total length.&nbsp;</em>It can be shown that there exists a unique solution of minimum total length.</p>



<p>Notice that you can return the substrings in&nbsp;<strong>any</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "adefaddaccc"
<strong>Output:</strong> ["e","f","ccc"]
<strong>Explanation:</strong>&nbsp;The following are all the possible substrings that meet the conditions:
[
&nbsp; "adefaddaccc"
&nbsp; "adefadda",
&nbsp; "ef",
&nbsp; "e",
  "f",
&nbsp; "ccc",
]
If we choose the first string, we cannot choose anything else and we'd get only 1. If we choose "adefadda", we are left with "ccc" which is the only one that doesn't overlap, thus obtaining 2 substrings. Notice also, that it's not optimal to choose "ef" since it can be split into two. Therefore, the optimal way is to choose ["e","f","ccc"] which gives us 3 substrings. No other solution of the same number of substrings exist.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abbaccd"
<strong>Output:</strong> ["d","bb","cc"]
<strong>Explanation: </strong>Notice that while the set of substrings ["d","abba","cc"] also has length 3, it's considered incorrect since it has larger total length.
</pre>



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



<ul><li><code>1 &lt;= s.length &lt;= 10^5</code></li><li><code>s</code>&nbsp;contains only lowercase English letters.</li></ul>



<h2><strong>Solution: Greedy</strong></h2>



<p>Observation: If a valid substring contains shorter valid strings, ignore the longer one and use the shorter one.<br>e.g. &#8220;abbeefba&#8221; is a valid substring, however, it includes &#8220;bbeefb&#8221;, &#8220;ee&#8221;, &#8220;f&#8221; three valid substrings, thus it won&#8217;t be part of the optimal solution, since we can always choose a shorter one, with potential to have one or more non-overlapping substrings. For &#8220;bbeefb&#8221;, again it includes &#8220;ee&#8221; and &#8220;f&#8221;, so it won&#8217;t be optimal either. Thus, the optimal ones are &#8220;ee&#8221; and &#8220;f&#8221;.</p>



<ol><li>We just need to record the first and last occurrence of each character</li><li>When we meet a character for the first time we must include everything from current pos to it&#8217;s last position. e.g. &#8220;<strong>a</strong>bbeefb<strong>a</strong>&#8221; | ccc, from first &#8216;a&#8217; to last &#8216;a&#8217;, we need to cover &#8220;abbeefba&#8221;</li><li>If any character in that range has larger end position, we must extend the string. e.g. &#8220;<strong>a</strong>bc<strong>a</strong>bbcc&#8221; | efg, from first &#8216;a&#8217; to last &#8216;a&#8217;, we have characters &#8216;b&#8217; and &#8216;c&#8217;, so we have to extend the string to cover all &#8216;b&#8217;s and &#8216;c&#8217;s. Our first valid substring extended from &#8220;abca&#8221; to &#8220;abcabbcc&#8221;.</li><li>If any character in the covered range has a smallest first occurrence, then it&#8217;s an invalid substring. e.g. ab | &#8220;cbc&#8221;, from first &#8216;c&#8217; to last &#8216;c&#8217;, we have &#8216;b&#8217;, but &#8216;b&#8217; is not fully covered, thus &#8220;cbc&#8221; is an invalid substring.</li><li>For the first valid substring, we append it to the ans array. &#8220;abbeefba&#8221; =&gt; ans = [&#8220;abbeefba&#8221;]</li><li>If we find a shorter substring that is full covered by the previous valid substring, we replace that substring with the shorter one. e.g.<br>&#8220;abbeefba&#8221; | ccc =&gt; ans = [&#8220;abbeefba&#8221;]<br>&#8220;<span style="text-decoration: underline;">a<strong>bbeefb</strong>a</span>&#8221; | ccc =&gt; ans = [&#8220;bbeefb&#8221;]<br>&#8220;a<span style="text-decoration: underline;">bb<strong>ee</strong>fb</span>a&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;]</li><li>If the current substring does not overlap with previous one, append it to ans array.<br>&#8220;abb<strong>ee</strong>fba&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;]<br>&#8220;abbee<strong>f</strong>ba&#8221; | ccc =&gt; ans = [&#8220;ee&#8221;, &#8220;f&#8221;]<br>&#8220;abbeefba<strong>ccc</strong>&#8221; =&gt; ans = [&#8220;ee&#8221;, &#8220;f&#8221;, &#8220;ccc&#8221;]</li></ol>



<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:
  vector&lt;string&gt; maxNumOfSubstrings(const string&amp; s) {
    const int n = s.length();    
    vector&lt;int&gt; l(26, INT_MAX);
    vector&lt;int&gt; r(26, INT_MIN);
    for (int i = 0; i &lt; n; ++i) {
      l[s[i] - 'a'] = min(l[s[i] - 'a'], i);
      r[s[i] - 'a'] = max(r[s[i] - 'a'], i);
    }
    auto extend = [&amp;](int i) -&gt; int {      
      int p = r[s[i] - 'a'];
      for (int j = i; j &lt;= p; ++j) {
        if (l[s[j] - 'a'] &lt; i) // invalid substring
          return -1; // e.g. a|&quot;ba&quot;...b
        p = max(p, r[s[j] - 'a']);
      }
      return p;
    };
    
    vector&lt;string&gt; ans;
    int last = -1;
    for (int i = 0; i &lt; n; ++i) {
      if (i != l[s[i] - 'a']) continue;
      int p = extend(i);
      if (p == -1) continue;
      if (i &gt; last) ans.push_back(&quot;&quot;);
      ans.back() = s.substr(i, p - i + 1);
      last = p;      
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-1520-maximum-number-of-non-overlapping-substrings/">花花酱 LeetCode 1520. Maximum Number of Non-Overlapping Substrings</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-1520-maximum-number-of-non-overlapping-substrings/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
