<?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>subarray Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/subarray/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/subarray/</link>
	<description></description>
	<lastBuildDate>Tue, 21 Dec 2021 06:08:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>subarray Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/subarray/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2110. Number of Smooth Descent Periods of a Stock</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2110-number-of-smooth-descent-periods-of-a-stock/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2110-number-of-smooth-descent-periods-of-a-stock/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 21 Dec 2021 06:08:17 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9188</guid>

					<description><![CDATA[<p>You are given an integer array&#160;prices&#160;representing the daily price history of a stock, where&#160;prices[i]&#160;is the stock price on the&#160;ith&#160;day. A&#160;smooth descent period&#160;of a stock consists&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2110-number-of-smooth-descent-periods-of-a-stock/">花花酱 LeetCode 2110. Number of Smooth Descent Periods of a Stock</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 an integer array&nbsp;<code>prices</code>&nbsp;representing the daily price history of a stock, where&nbsp;<code>prices[i]</code>&nbsp;is the stock price on the&nbsp;<code>i<sup>th</sup></code>&nbsp;day.</p>



<p>A&nbsp;<strong>smooth descent period</strong>&nbsp;of a stock consists of&nbsp;<strong>one or more contiguous</strong>&nbsp;days such that the price on each day is&nbsp;<strong>lower</strong>&nbsp;than the price on the&nbsp;<strong>preceding day</strong>&nbsp;by&nbsp;<strong>exactly</strong>&nbsp;<code>1</code>. The first day of the period is exempted from this rule.</p>



<p>Return&nbsp;<em>the number of&nbsp;<strong>smooth descent periods</strong></em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [3,2,1,4]
<strong>Output:</strong> 7
<strong>Explanation:</strong> There are 7 smooth descent periods:
[3], [2], [1], [4], [3,2], [2,1], and [3,2,1]
Note that a period with one day is a smooth descent period by the definition.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [8,6,7,7]
<strong>Output:</strong> 4
<strong>Explanation:</strong> There are 4 smooth descent periods: [8], [6], [7], and [7]
Note that [8,6] is not a smooth descent period as 8 - 6 ≠ 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> prices = [1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is 1 smooth descent period: [1]
</pre>



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



<ul><li><code>1 &lt;= prices.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= prices[i] &lt;= 10<sup>5</sup></code></li></ul>



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



<p>Same as longest decreasing subarray. </p>



<p>dp[i] := length of longest smoothing subarray ends with nums[i].</p>



<p>dp[i] = dp[i &#8211; 1] + 1 if nums[i] + 1 = nums[i &#8211; 1] else 1</p>



<p>Time complexity: O(n)<br>Space complexity: O(n) -&gt; O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long getDescentPeriods(vector&lt;int&gt;&amp; prices) {
    const int n = prices.size();
    vector&lt;long long&gt; dp(n, 1);
    long long ans = 1;
    for (int i = 1; i &lt; n; ++i) {
      if (prices[i] - prices[i - 1] == -1)
        dp[i] = dp[i - 1] + 1;    
      ans += dp[i];
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2110-number-of-smooth-descent-periods-of-a-stock/">花花酱 LeetCode 2110. Number of Smooth Descent Periods of a Stock</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-2110-number-of-smooth-descent-periods-of-a-stock/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2104. Sum of Subarray Ranges</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2104-sum-of-subarray-ranges/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2104-sum-of-subarray-ranges/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Dec 2021 23:20:21 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9162</guid>

					<description><![CDATA[<p>Problem Solution 0: Brute force [TLE] Enumerate all subarrays, for each one, find min and max. Time complexity: O(n3)Space complexity: O(1) Solution 1: Prefix min/max&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2104-sum-of-subarray-ranges/">花花酱 LeetCode 2104. Sum of Subarray Ranges</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2><strong><a href="https://leetcode.com/problems/sum-of-subarray-ranges/">Problem</a></strong></h2>



<p></p>



<h2><strong>Solution 0: Brute force</strong> <span class="has-inline-color has-vivid-red-color"><strong>[TLE]</strong></span></h2>



<p>Enumerate all subarrays, for each one, find min and max.</p>



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



<h2><strong>Solution 1: Prefix min/max</strong></h2>



<p>We can use prefix technique to extend the array while keep tracking the min/max of the subarray.</p>



<p>Time complexity: O(n<sup>2</sup>)<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:
  long long subArrayRanges(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();    
    long long ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      int lo = nums[i];
      int hi = nums[i];
      for (int j = i + 1; j &lt; n; ++j) {
        lo = min(lo, nums[j]);
        hi = max(hi, nums[j]);
        ans += (hi - lo);
      }
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Monotonic stack</strong></h2>



<p>This problem can be reduced to <a href="https://zxi.mytechroad.com/blog/stack/leetcode-907-sum-of-subarray-minimums/" data-type="post" data-id="3987">花花酱 LeetCode 907. Sum of Subarray Minimums</a></p>



<p>Just need to run twice one for sum of mins and another for sum of maxs.</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:
  long long subArrayRanges(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    auto sumOf = [&amp;](function&lt;bool(int, int)&gt; op) {
      long long ans = 0;
      stack&lt;int&gt; s;
      for (long long i = 0; i &lt;= n; ++i) {
        while (!s.empty() and (i == n or op(nums[s.top()], nums[i]))) {
          long long k = s.top(); s.pop();
          long long j = s.empty() ? -1 : s.top();
          ans += nums[k] * (i - k) * (k - j);
        }
        s.push(i);
      }
      return ans;
    };
    return sumOf(less&lt;int&gt;()) - sumOf(greater&lt;int&gt;());
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2104-sum-of-subarray-ranges/">花花酱 LeetCode 2104. Sum of Subarray Ranges</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/array/leetcode-2104-sum-of-subarray-ranges/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 76. Minimum Window Substring</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-76-minimum-window-substring/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-76-minimum-window-substring/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 16:43:58 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8940</guid>

					<description><![CDATA[<p>Given two strings&#160;s&#160;and&#160;t&#160;of lengths&#160;m&#160;and&#160;n&#160;respectively, return&#160;the&#160;minimum window substring&#160;of&#160;s&#160;such that every character in&#160;t&#160;(including duplicates) is included in the window. If there is no such substring, return the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-76-minimum-window-substring/">花花酱 LeetCode 76. Minimum Window Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given two strings&nbsp;<code>s</code>&nbsp;and&nbsp;<code>t</code>&nbsp;of lengths&nbsp;<code>m</code>&nbsp;and&nbsp;<code>n</code>&nbsp;respectively, return&nbsp;<em>the&nbsp;<strong>minimum window substring</strong>&nbsp;of&nbsp;</em><code>s</code><em>&nbsp;such that every character in&nbsp;</em><code>t</code><em>&nbsp;(<strong>including duplicates</strong>) is included in the window. If there is no such substring</em><em>, return the empty string&nbsp;</em><code>""</code><em>.</em></p>



<p>The testcases will be generated such that the answer is&nbsp;<strong>unique</strong>.</p>



<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous sequence of characters within the string.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ADOBECODEBANC", t = "ABC"
<strong>Output:</strong> "BANC"
<strong>Explanation:</strong> The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a", t = "a"
<strong>Output:</strong> "a"
<strong>Explanation:</strong> The entire string s is the minimum window.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "a", t = "aa"
<strong>Output:</strong> ""
<strong>Explanation:</strong> Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
</pre>



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



<ul><li><code>m == s.length</code></li><li><code>n == t.length</code></li><li><code>1 &lt;= m, n&nbsp;&lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;and&nbsp;<code>t</code>&nbsp;consist of uppercase and lowercase English letters.</li></ul>



<p><strong>Follow up:</strong>&nbsp;Could you find an algorithm that runs in&nbsp;<code>O(m + n)</code>&nbsp;time?</p>



<h2><strong>Solution: Hashtable + Two Pointers</strong></h2>



<p>Use a hashtable to store the freq of characters we need to match for t.</p>



<p>Use (i, j) to track a subarray that contains all the chars in t.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  string minWindow(string s, string t) {
    const int n = s.length();
    const int m = t.length();
    vector&lt;int&gt; freq(128);
    for (char c : t) ++freq[c];
    int start = 0;
    int l = INT_MAX;    
    for (int i = 0, j = 0, left = m; j &lt; n; ++j) {
      if (--freq[s[j]] &gt;= 0) --left;
      while (left == 0) {
        if (j - i + 1 &lt; l) {
          l = j - i + 1;
          start = i;
        }
        if (++freq[s[i++]] == 1) ++left;
      }
    }
    return l == INT_MAX ? &quot;&quot; : s.substr(start, l);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-76-minimum-window-substring/">花花酱 LeetCode 76. Minimum Window Substring</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-76-minimum-window-substring/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 152. Maximum Product Subarray</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-152-maximum-product-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-152-maximum-product-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 06:22:18 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8914</guid>

					<description><![CDATA[<p>Given an integer array&#160;nums, find a contiguous non-empty subarray within the array that has the largest product, and return&#160;the product. It is&#160;guaranteed&#160;that the answer will&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-152-maximum-product-subarray/">花花酱 LeetCode 152. Maximum Product Subarray</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 integer array&nbsp;<code>nums</code>, find a contiguous non-empty subarray within the array that has the largest product, and return&nbsp;<em>the product</em>.</p>



<p>It is&nbsp;<strong>guaranteed</strong>&nbsp;that the answer will fit in a&nbsp;<strong>32-bit</strong>&nbsp;integer.</p>



<p>A&nbsp;<strong>subarray</strong>&nbsp;is a contiguous subsequence of the array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,-2,4]
<strong>Output:</strong> 6
<strong>Explanation:</strong> [2,3] has the largest product 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-2,0,-1]
<strong>Output:</strong> 0
<strong>Explanation:</strong> The result cannot be 2, because [-2,-1] is not a subarray.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li><li><code>-10 &lt;= nums[i] &lt;= 10</code></li><li>The product of any prefix or suffix of&nbsp;<code>nums</code>&nbsp;is&nbsp;<strong>guaranteed</strong>&nbsp;to fit in a&nbsp;<strong>32-bit</strong>&nbsp;integer.</li></ul>



<h2><strong>Solution: Track high and low</strong></h2>



<p>Compute the low / high of prefix product, reset if nums[i] is higher than high or lower than low.</p>



<p>Swap low and high if nums[i] is a negative number.</p>



<p>e.g. [2, 3, -1, 8, -2]<br>nums[i] = 2, low = 2, high = 2<br>nums[i] = 3, low = 3, high = 2 * 3 = 6<br>nums[i] = -1, low = 6 * -1 = -6, high = -1<br>nums[i] = 8, low = -6 * 8 = -48, high = 8<br>nums[i] = -2, low = 8*-2 = -16, high = -48 * -2 = <strong><span class="has-inline-color has-vivid-red-color">96</span></strong></p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxProduct(vector&lt;int&gt;&amp; nums) {   
    int ans = nums[0];
    for (int i = 1, h = ans, l = ans; i &lt; nums.size(); ++i) {
      if (nums[i] &lt; 0) swap(l, h);
      l = min(nums[i], nums[i] * l);
      h = max(nums[i], nums[i] * h);
      ans = max(ans, h);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-152-maximum-product-subarray/">花花酱 LeetCode 152. Maximum Product Subarray</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/array/leetcode-152-maximum-product-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2009. Minimum Number of Operations to Make Array Continuous</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 26 Nov 2021 20:32:13 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[unique]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8780</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums. In one operation, you can replace&#160;any&#160;element in&#160;nums&#160;with&#160;any&#160;integer. nums&#160;is considered&#160;continuous&#160;if both of the following conditions are fulfilled: All elements in&#160;nums&#160;are&#160;unique.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/">花花酱 LeetCode 2009. Minimum Number of Operations to Make Array Continuous</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 an integer array&nbsp;<code>nums</code>. In one operation, you can replace&nbsp;<strong>any</strong>&nbsp;element in&nbsp;<code>nums</code>&nbsp;with&nbsp;<strong>any</strong>&nbsp;integer.</p>



<p><code>nums</code>&nbsp;is considered&nbsp;<strong>continuous</strong>&nbsp;if both of the following conditions are fulfilled:</p>



<ul><li>All elements in&nbsp;<code>nums</code>&nbsp;are&nbsp;<strong>unique</strong>.</li><li>The difference between the&nbsp;<strong>maximum</strong>&nbsp;element and the&nbsp;<strong>minimum</strong>&nbsp;element in&nbsp;<code>nums</code>&nbsp;equals&nbsp;<code>nums.length - 1</code>.</li></ul>



<p>For example,&nbsp;<code>nums = [4, 2, 5, 3]</code>&nbsp;is&nbsp;<strong>continuous</strong>, but&nbsp;<code>nums = [1, 2, 3, 5, 6]</code>&nbsp;is&nbsp;<strong>not continuous</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of operations to make&nbsp;</em><code>nums</code><strong><em>continuous</em></strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,5,3]
<strong>Output:</strong> 0
<strong>Explanation:</strong>&nbsp;nums is already continuous.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,5,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong>&nbsp;One possible solution is to change the last element to 4.
The resulting array is [1,2,3,5,4], which is continuous.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,10,100,1000]
<strong>Output:</strong> 3
<strong>Explanation:</strong>&nbsp;One possible solution is to:
- Change the second element to 2.
- Change the third element to 3.
- Change the fourth element to 4.
The resulting array is [1,2,3,4], which is continuous.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li></ul>



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



<p>Remove duplicates and sort the numbers.<br>Try using nums[i] as the min number of the final array.<br>window [i, j), max &#8211; min &lt; n, then change the rest of array to fit into or append after the window, which takes n &#8211; (j &#8211; i) steps.<br>e.g. input = [10, 3, 1, 4, 5, 6, 6, 6, 11, 15] => sorted + unique => [1, 3, 4, 5, 6, 10, 11, 15]<br>n = 10, window = [3, 4, 5, 6, 10, 11], max = 11, min = 3, max &#8211; min = 8 &lt; 10<br>Final array = [3, 4, 5, 6, <strong><span class="has-inline-color has-vivid-red-color">1->7, 6<sub>2</sub>->8, 6<sub>3</sub>->9</span></strong>, 10, 11, <strong><span class="has-inline-color has-vivid-red-color">15->12</span></strong>] <br>Time complexity: O(n)<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; A) {
    const int n = A.size();
    sort(begin(A), end(A));
    A.erase(unique(begin(A), end(A)), end(A));    
    int ans = INT_MAX;
    for (int i = 0, j = 0, m = A.size(); i &lt; m; ++i) {
      while (j &lt; m &amp;&amp; A[j] &lt; A[i] + n) ++j;
      ans = min(ans, n - (j - i));
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/">花花酱 LeetCode 2009. Minimum Number of Operations to Make Array Continuous</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/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 06 Feb 2021 16:24:40 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8065</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums. The&#160;absolute sum&#160;of a subarray&#160;[numsl, numsl+1, ..., numsr-1, numsr]&#160;is&#160;abs(numsl&#160;+ numsl+1&#160;+ ... + numsr-1&#160;+ numsr). Return&#160;the&#160;maximum&#160;absolute sum of any&#160;(possibly empty)&#160;subarray of&#160;nums.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/">花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</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 an integer array&nbsp;<code>nums</code>. The&nbsp;<strong>absolute sum</strong>&nbsp;of a subarray&nbsp;<code>[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>]</code>&nbsp;is&nbsp;<code>abs(nums<sub>l</sub>&nbsp;+ nums<sub>l+1</sub>&nbsp;+ ... + nums<sub>r-1</sub>&nbsp;+ nums<sub>r</sub>)</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;absolute sum of any&nbsp;<strong>(possibly empty)</strong>&nbsp;subarray of&nbsp;</em><code>nums</code>.</p>



<p>Note that&nbsp;<code>abs(x)</code>&nbsp;is defined as follows:</p>



<ul><li>If&nbsp;<code>x</code>&nbsp;is a negative integer, then&nbsp;<code>abs(x) = -x</code>.</li><li>If&nbsp;<code>x</code>&nbsp;is a non-negative integer, then&nbsp;<code>abs(x) = x</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-3,2,3,-4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,-5,1,-4,3,-2]
<strong>Output:</strong> 8
<strong>Explanation:</strong> The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
</pre>



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



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



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



<p>ans = max{abs(prefix_sum[i] &#8211; max(prefix_sum[0:i])), abs(prefix_sum &#8211; min(prefix_sum[0: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">// Author: Huahua
class Solution {
public:
  int maxAbsoluteSum(vector&lt;int&gt;&amp; nums) {
    int lo = 0;
    int hi = 0;
    int s = 0;
    int ans = 0;
    for (int x : nums) {
      s += x;
      ans = max({ans, abs(s - lo), abs(s - hi)});
      hi = max(hi, s);
      lo = min(lo, s);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/">花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</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/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 1513. Number of Substrings With Only 1s</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1513-number-of-substrings-with-only-1s/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1513-number-of-substrings-with-only-1s/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 29 Jul 2020 19:12:56 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7180</guid>

					<description><![CDATA[<p>Given a binary string&#160;s&#160;(a string consisting only of &#8216;0&#8217; and &#8216;1&#8217;s). Return the number of substrings with all characters 1&#8217;s. Since the answer&#160;may be too&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1513-number-of-substrings-with-only-1s/">花花酱 LeetCode 1513. Number of Substrings With Only 1s</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 binary string&nbsp;<code>s</code>&nbsp;(a string consisting only of &#8216;0&#8217; and &#8216;1&#8217;s).</p>



<p>Return the number of substrings with all characters 1&#8217;s.</p>



<p>Since the answer&nbsp;may be too large,&nbsp;return it modulo&nbsp;10^9 + 7.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "0110111"
<strong>Output:</strong> 9
<strong>Explanation: </strong>There are 9 substring in total with only 1's characters.
"1" -&gt; 5 times.
"11" -&gt; 3 times.
"111" -&gt; 1 time.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "101"
<strong>Output:</strong> 2
<strong>Explanation: </strong>Substring "1" is shown 2 times in s.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "111111"
<strong>Output:</strong> 21
<strong>Explanation: </strong>Each substring contains only 1's characters.
</pre>



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



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



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



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



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



<p>dp[i] := # of all 1 subarrays end with s[i].<br>dp[i] = dp[i-1] if s[i] == ‘1‘ else 0<br>ans = sum(dp)<br>s=1101<br>dp[0] = 1 // 1<br>dp[1] = 2 // 11, *1<br>dp[2] = 0 // None<br>dp[3] = 1 // ***1<br>ans = 1 + 2 + 1 = 5</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 numSub(string s) {
    constexpr int kMod = 1e9 + 7;
    long ans = 0;
    vector&lt;int&gt; dp(s.length() + 1);
    for (int i = 1; i &lt;= s.length(); ++i) {
      dp[i] = s[i - 1] == '1' ? dp[i - 1] + 1 : 0;
      ans += dp[i];
    }
    return ans % kMod;
  }
};</pre> 
</div></div>



<p>dp[i] only depends on dp[i-1], we can reduce the space complexity to O(1)</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int numSub(string s) {
    constexpr int kMod = 1e9 + 7;
    long ans = 0;
    int cur = 0;
    for (char c : s) {
      cur = c == '1' ? cur + 1 : 0;
      ans += cur;
    }
    return ans % kMod;
  }
};</pre> 

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

<pre class="crayon-plain-tag">class Solution {
  public int numSub(String s) {
    final int kMod = 1_000_000_000 + 7;
    int ans = 0;
    int cur = 0;
    for (int i = 0; i &lt; s.length(); ++i) {
      cur = s.charAt(i) == '1' ? cur + 1 : 0;
      ans = (ans + cur) % kMod;
    }
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def numSub(self, s: str) -&gt; int:
    kMod = 10**9 + 7
    ans = 0
    cur = 0
    for c in s:
      cur = cur + 1 if c == '1' else 0
      ans += cur
    return ans % kMod</pre>
</div></div>



<p><br></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1513-number-of-substrings-with-only-1s/">花花酱 LeetCode 1513. Number of Substrings With Only 1s</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-1513-number-of-substrings-with-only-1s/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>
		<item>
		<title>花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Jul 2020 04:22:08 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7071</guid>

					<description><![CDATA[<p>Given the array&#160;nums&#160;consisting of&#160;n&#160;positive integers. You computed the sum of all non-empty continous subarrays from&#160;the array and then sort them in non-decreasing order, creating a&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/">花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</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 1508. Range Sum of Sorted Subarray Sums - 刷题找工作 EP343" width="500" height="281" src="https://www.youtube.com/embed/6UJEMVmMJDw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given the array&nbsp;<code>nums</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;positive integers. You computed the sum of all non-empty continous subarrays from&nbsp;the array and then sort them in non-decreasing order, creating a new array of&nbsp;<code>n * (n + 1) / 2</code>&nbsp;numbers.</p>



<p><em>Return the sum of the numbers from index&nbsp;</em><code>left</code><em>&nbsp;to index&nbsp;</em><code>right</code>&nbsp;(<strong>indexed from 1</strong>)<em>, inclusive, in the&nbsp;new array.&nbsp;</em>Since the answer can be a huge number return it modulo 10^9 + 7.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 5
<strong>Output:</strong> 13 
<strong>Explanation:</strong> All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 3, right = 4
<strong>Output:</strong> 6
<strong>Explanation:</strong> The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4], n = 4, left = 1, right = 10
<strong>Output:</strong> 50
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10^3</code></li><li><code>nums.length == n</code></li><li><code>1 &lt;= nums[i] &lt;= 100</code></li><li><code>1 &lt;= left &lt;= right&nbsp;&lt;= n * (n + 1) / 2</code></li></ul>



<h2><strong>Solution 1: Brute Force</strong></h2>



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



<p>Find sums of all the subarrays and sort the values.</p>



<p>Time complexity: O(n^2logn)<br>Space complexity: O(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 rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;
    vector&lt;int&gt; sums;
    for (int i = 0; i &lt; n; ++i)      
      for (int j = i, sum = 0; j &lt; n; ++j)
        sums.push_back(sum += nums[j]);
    sort(begin(sums), end(sums));
    return accumulate(begin(sums) + left - 1, begin(sums) + right, 0LL) % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
  public int rangeSum(int[] nums, int n, int left, int right) {
    final int kMod = (int)(1e9 + 7);
    int[] sums = new int[n * (n + 1) / 2];
    int idx = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = i, sum = 0; j &lt; n; ++j, ++idx)
        sums[idx] = sum += nums[j];
    Arrays.sort(sums);
    int ans = 0;
    for (int i = left; i &lt;= right; ++i)
      ans = (ans + sums[i - 1]) % kMod;
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def rangeSum(self, nums: List[int], n: int, left: int, right: int) -&gt; int:
    sums = []
    for i in range(n):
      s = 0
      for j in range(i, n):
        s += nums[j]
        sums.append(s)
    sums.sort()
    return sum(sums[left - 1:right])</pre>
</div></div>



<h2><strong>Solution 2: Priority Queue</strong> <strong>/ Min Heap</strong></h2>



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



<p>For each subarray, start with one element e.g nums[i], put them into a priority queue (min heap). Each time, we have the smallest subarray sum, and extend that subarray and put the new sum back into priority queue. Thought it has the same time complexity as the brute force one in worst case, but space complexity can be reduce to O(n).</p>



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



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

<pre class="crayon-plain-tag">struct Entry {
  int sum;
  int i;
  bool operator&lt;(const Entry&amp; e) const { return sum &gt; e.sum; }
};

class Solution {
public:
  int rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;
    priority_queue&lt;Entry&gt; q; // Sort by e.sum in descending order.
    for (int i = 0; i &lt; n; ++i)
      q.push({nums[i], i});
    long ans = 0;
    for (int j = 1; j &lt;= right; ++j) {
      const auto e = std::move(q.top()); q.pop();
      if (j &gt;= left) ans += e.sum;
      if (e.i + 1 &lt; n) q.push({e.sum + nums[e.i + 1], e.i + 1});
    }
    return ans % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">import java.util.AbstractMap;
class Solution {
  public int rangeSum(int[] nums, int n, int left, int right) {
    final int kMod = (int)(1e9 + 7);
    var q = new PriorityQueue&lt;Map.Entry&lt;Integer, Integer&gt;&gt;((a, b) -&gt; a.getKey() - b.getKey());
    for (int i = 0; i &lt; n; ++i)
      q.offer(new AbstractMap.SimpleEntry&lt;&gt;(nums[i], i));
    
    int ans = 0;
    for (int k = 1; k &lt;= right; ++k) {      
      var e = q.poll();
      int sum = e.getKey();
      int i = e.getValue();
      if (k &gt;= left) 
        ans = (ans + sum) % kMod;
      if (i + 1 &lt; n) 
        q.offer(new AbstractMap.SimpleEntry&lt;&gt;(sum + nums[i + 1], i + 1));
    }
    return ans;
  }
}</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def rangeSum(self, nums: List[int], n: int, left: int, right: int) -&gt; int:
    q = [(num, i) for i, num in enumerate(nums)]
    heapq.heapify(q)
    ans = 0
    for k in range(1, right + 1):
      s, i = heapq.heappop(q)
      if k &gt;= left:
        ans += s
      if i + 1 &lt; n:
        heapq.heappush(q, (s + nums[i + 1], i + 1))
    return ans % int(1e9 + 7)</pre>
</div></div>



<h2><strong>Solution 3: Binary Search + Sliding Window</strong></h2>



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



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



<p>Use binary search to find S s.t. that there are at least k subarrys have sum &lt;= S.</p>



<p>Given S, we can use sliding window to count how many subarrays have sum &lt;= S and their total sum.</p>



<p>ans = sums_of_first(right) &#8211; sums_of_first(left &#8211; 1).</p>



<p>Time complexity: O(n * log(sum(nums))<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 rangeSum(vector&lt;int&gt;&amp; nums, int n, int left, int right) {
    constexpr int kMod = 1e9 + 7;    
    // Returns number of subarrays that have 
    // sum &lt;= target and their total sum.
    auto countAndSum = [&amp;](int target) -&gt; pair&lt;int, long&gt; {
      int count = 0;
      long cur = 0;
      long sum = 0;
      long total_sum = 0;
      for (long j = 0, i = 0; j &lt; n; ++j) {
        cur += nums[j];
        sum += nums[j] * (j - i + 1);
        while (cur &gt; target) {          
          sum -= cur;
          cur -= nums[i++];
        }        
        count += j - i + 1;
        total_sum += sum;
      }
      return {count, total_sum};
    };
    
    // Returns the total sums of smallest k subarrays.
    // Use binary search to find the smallest sum l s.t. 
    // there are at least k of subarrays have sums &lt;= l.
    const int min_sum = *min_element(begin(nums), end(nums));
    const int max_sum = accumulate(begin(nums), end(nums), 0) + 1;
    auto sumOfFirstK = [&amp;](int k) -&gt; long {
      int l = min_sum;
      int r = max_sum;
      while (l &lt; r) {
        int mid = l + (r - l) / 2;
        if (countAndSum(mid).first &gt;= k)
          r = mid;
        else
          l = mid + 1;
      }      
      const auto [count, sum] = countAndSum(l);
      // There can be more subarrays have the same sum of l.      
      return sum - l * (count - k);
    };
    
    return (sumOfFirstK(right) - sumOfFirstK(left - 1)) % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/">花花酱 LeetCode 1508. Range Sum of Sorted Subarray Sums</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/queue/leetcode-1508-range-sum-of-sorted-subarray-sums/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1493. Longest Subarray of 1&#8217;s After Deleting One Element</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Jun 2020 20:35:09 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[longest]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6975</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

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



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



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



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



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

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



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



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



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int ans = 0;
    int sum = 0; // sum of nums[l~r].
    for (int l = 0, r = 0; r &lt; n; ++r) {
      sum += nums[r];
      // Maintain sum &gt;= r - l, at most 1 zero.
      while (l &lt; r &amp;&amp; sum &lt; r - l)
        sum -= nums[l++];
      ans = max(ans, r - l);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/">花花酱 LeetCode 1493. Longest Subarray of 1&#8217;s After Deleting One Element</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1493-longest-subarray-of-1s-after-deleting-one-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Jun 2020 04:40:34 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[target sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6912</guid>

					<description><![CDATA[<p>Given an array of integers&#160;arr&#160;and an integer&#160;target. You have to find&#160;two non-overlapping sub-arrays&#160;of&#160;arr&#160;each with sum equal&#160;target. There can be multiple answers so you have to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/">花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum</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 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum - 刷题找工作 EP335" width="500" height="375" src="https://www.youtube.com/embed/AeIxJrzx9MU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array of integers&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>target</code>.</p>



<p>You have to find&nbsp;<strong>two non-overlapping sub-arrays</strong>&nbsp;of&nbsp;<code>arr</code>&nbsp;each with sum equal&nbsp;<code>target</code>. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is&nbsp;<strong>minimum</strong>.</p>



<p>Return&nbsp;<em>the minimum sum of the lengths</em>&nbsp;of the two required sub-arrays, or return&nbsp;<em><strong>-1</strong></em>&nbsp;if you cannot&nbsp;find such two sub-arrays.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,2,2,4,3], target = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [7,3,4,7], target = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,3,2,6,2,3,4], target = 6
<strong>Output:</strong> -1
<strong>Explanation:</strong> We have only one sub-array of sum = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [5,5,4,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> We cannot find a sub-array of sum = 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,1,1,1,5,1,2,1], target = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;= 10^5</code></li><li><code>1 &lt;= arr[i] &lt;= 1000</code></li><li><code>1 &lt;= target &lt;= 10^8</code></li></ul>



<h2><strong>Solution: Sliding Window + Best so far</strong></h2>



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



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



<ol><li>Use a sliding window to maintain a subarray whose sum is &lt;= target</li><li>When the sum of the sliding window equals to target, we found a subarray [s, e]</li><li>Update ans with it&#8217;s length + shortest subarray which ends before s.</li><li>We can use an array to store the shortest subarray which ends before s.</li></ol>



<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 minSumOfLengths(vector&lt;int&gt;&amp; arr, int target) {
    constexpr int kInf = 1e9;
    const int n = arr.size();
    // min_lens[i] := min length of a valid subarray ends or before i.
    vector&lt;int&gt; min_lens(n, kInf);
    int ans = kInf;
    int sum = 0;
    int s = 0;
    int min_len = kInf;
    for (int e = 0; e &lt; n; ++e) {
      sum += arr[e];
      while (sum &gt; target) sum -= arr[s++];
      if (sum == target) {       
        const int cur_len = e - s + 1;
        if (s &gt; 0 &amp;&amp; min_lens[s - 1] != kInf)
          ans = min(ans, cur_len + min_lens[s - 1]);
        min_len = min(min_len, cur_len);
      }
      min_lens[e] = min_len;
    }    
    return ans &gt;= kInf ? -1 : ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/">花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum</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/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 14 Feb 2020 06:28:10 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[k]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6306</guid>

					<description><![CDATA[<p>Given an array of integers&#160;arr&#160;and two integers&#160;k&#160;and&#160;threshold. Return&#160;the number of sub-arrays&#160;of size&#160;k&#160;and average greater than or equal to&#160;threshold. Example 1: Input: arr = [2,2,2,2,5,5,5,8], k&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/">花花酱 LeetCode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold</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 of integers&nbsp;<code>arr</code>&nbsp;and two integers&nbsp;<code>k</code>&nbsp;and&nbsp;<code>threshold</code>.</p>



<p>Return&nbsp;<em>the number of sub-arrays</em>&nbsp;of size&nbsp;<code>k</code>&nbsp;and average greater than or equal to&nbsp;<code>threshold</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,2,2,2,5,5,5,8], k = 3, threshold = 4
<strong>Output:</strong> 3
<strong>Explanation:</strong> Sub-arrays [2,5,5],[5,5,5] and [5,5,8] have averages 4, 5 and 6 respectively. All other sub-arrays of size 3 have averages less than 4 (the threshold).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,1,1,1,1], k = 1, threshold = 0
<strong>Output:</strong> 5
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [11,13,17,23,29,31,7,5,2,3], k = 3, threshold = 5
<strong>Output:</strong> 6
<strong>Explanation:</strong> The first 6 sub-arrays of size 3 have averages greater than 5. Note that averages are not integers.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [7,7,7,7,7,7,7], k = 7, threshold = 7
<strong>Output:</strong> 1
</pre>



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



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



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



<ul><li><code>1 &lt;= arr.length &lt;= 10^5</code></li><li><code>1 &lt;= arr[i] &lt;= 10^4</code></li><li><code>1 &lt;= k &lt;= arr.length</code></li><li><code>0 &lt;= threshold &lt;= 10^4</code></li></ul>



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



<ol><li>Window size = k</li><li>Maintain the sum of the window</li><li>Check sum &gt;= threshold * k</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:
  int numOfSubarrays(vector&lt;int&gt;&amp; arr, int k, int threshold) {
    int ans = 0;
    int sum = 0;
    for (int i = 0; i &lt; arr.size(); ++i) {
      sum += arr[i];
      if (i + 1 &gt;= k) {
        if (threshold * k &lt;= sum) ++ans;
        sum -= arr[i + 1 - k];
      } 
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/">花花酱 LeetCode 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold</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/sliding-window/leetcode-1343-number-of-sub-arrays-of-size-k-and-average-greater-than-or-equal-to-threshold/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Sep 2019 04:23:10 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5534</guid>

					<description><![CDATA[<p>Given an array of integers, return the maximum sum for a&#160;non-empty&#160;subarray (contiguous elements) with at most one element deletion.&#160;In other words, you want to choose&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/">花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion</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 of integers, return the maximum sum for a&nbsp;<strong>non-empty</strong>&nbsp;subarray (contiguous elements) with at most one element deletion.&nbsp;In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the&nbsp;sum of the remaining elements is maximum possible.</p>



<p>Note that the subarray needs to be&nbsp;<strong>non-empty</strong>&nbsp;after deleting one element.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,-2,0,3]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,-2,-2,3]
<strong>Output:</strong> 3
<strong>Explanation: </strong>We just choose [3] and it's the maximum sum.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [-1,-1,-1,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong>&nbsp;The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
</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] &lt;= 10^4</code></li></ul>



<p><strong>Solution: DP</strong></p>



<p>First, handle the special case: all numbers are negative, return the max one.</p>



<p>s0 = max subarray sum ends with a[i]<br>s1 = max subarray sum ends with a[i] with at most one deletion</p>



<p>whenever s0 or s1 becomes negative, reset them to 0.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumSum(vector&lt;int&gt;&amp; arr) {    
    int m = *max_element(begin(arr), end(arr));
    if (m &lt;= 0) return m;
    
    int s0 = 0;
    int s1 = 0;
    int ans = 0;
    
    for (int a : arr) {
      s1 = max(s0, s1 + a);
      s0 += a;
      ans = max(ans, max(s0, s1));
      if (s0 &lt; 0) s0 = 0;
      if (s1 &lt; 0) s1 = 0;
    }
    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/">花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion</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-1186-maximum-subarray-sum-with-one-deletion/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 718. Maximum Length of Repeated Subarray</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-718-maximum-length-of-repeated-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-718-maximum-length-of-repeated-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 18 May 2019 04:58:48 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5201</guid>

					<description><![CDATA[<p>iven two integer arrays&#160;A&#160;and&#160;B, return the maximum length of an subarray that appears in both arrays. Example 1: Input: A: [1,2,3,2,1] B: [3,2,1,4,7] Output: 3&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-718-maximum-length-of-repeated-subarray/">花花酱 LeetCode 718. Maximum Length of Repeated Subarray</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>iven two integer arrays&nbsp;<code>A</code>&nbsp;and&nbsp;<code>B</code>, return the maximum length of an subarray that appears in both arrays.</p>



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



<pre class="wp-block-preformatted; crayon:false"><strong>Input:</strong>
A: [1,2,3,2,1]
B: [3,2,1,4,7]
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
The repeated subarray with maximum length is [3, 2, 1].
</pre>



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



<ol><li>1 &lt;= len(A), len(B) &lt;= 1000</li><li>0 &lt;= A[i], B[i] &lt; 100</li></ol>



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



<p>dp[i][j] := max length of (A[0:i], B[0:j])</p>



<p>dp[i][j] = dp[i &#8211; 1][j &#8211; 1] + 1 if A[i-1] == B[j-1] else 0</p>



<p>Time complexity: O(m*n)<br>Space complexity: O(m*n) -&gt; O(n)</p>



<div class="responsive-tabs">
<h2 class="tabtitle">C++ S:O(mn)</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 176 ms / 106.4 MB
class Solution {
public:
  int findLength(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    int m = A.size();
    int n = B.size();
    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n + 1));    
    int ans = 0;
    for (int i = 1; i &lt;= m; ++i)
      for (int j = 1; j &lt;= n; ++j)
        if (A[i - 1] == B[j - 1]) {
          dp[i][j] = dp[i - 1][j - 1] + 1;
          ans = max(ans, dp[i][j]);
        }
    return ans;
  }
};</pre>

</div><h2 class="tabtitle">C++ S:O(min(m,n))</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 152 ms / 9.1 MB
class Solution {
public:
  int findLength(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    if (A.size() &lt; B.size()) swap(A, B);
    int m = A.size();
    int n = B.size();
    vector&lt;int&gt; dp(n + 1);    
    int ans = 0;
    for (int i = 1; i &lt;= m; ++i)
      for (int j = n; j &gt;= 1; --j) {
        dp[j] = A[i - 1] == B[j - 1] ? dp[j - 1] + 1 : 0;        
        ans = max(ans, dp[j]);
      }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-718-maximum-length-of-repeated-subarray/">花花酱 LeetCode 718. Maximum Length of Repeated Subarray</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-718-maximum-length-of-repeated-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
