<?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>Two pointers Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/two-pointers/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/two-pointers/</link>
	<description></description>
	<lastBuildDate>Thu, 24 Aug 2023 04:44:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>Two pointers Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/two-pointers/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2825. Make String a Subsequence Using Cyclic Increments</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 24 Aug 2023 04:38:17 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[subsequence]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10077</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



<p>If matched: ++i; ++j else ++i.</p>



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



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

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



<p>Iterator version</p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  bool canMakeSubsequence(string_view s1, string_view s2) {    
    for (auto i = begin(s1), j = begin(s2); i != end(s1); ++i)
      if (*i == *j || (*i - 'a' + 1) % 26 == *j - 'a')
        if (++j == end(s2)) return true;
    return false;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/">花花酱 LeetCode 2825. Make String a Subsequence Using Cyclic Increments</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2825-make-string-a-subsequence-using-cyclic-increments/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 2570. Merge Two 2D Arrays by Summing Values</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/2570-merge-two-2d-arrays-by-summing-values/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/2570-merge-two-2d-arrays-by-summing-values/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 19 Feb 2023 06:01:11 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9960</guid>

					<description><![CDATA[<p>You are given two&#160;2D&#160;integer arrays&#160;nums1&#160;and&#160;nums2. nums1[i] = [idi, vali]&#160;indicate that the number with the id&#160;idi&#160;has a value equal to&#160;vali. nums2[i] = [idi, vali]&#160;indicate that the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/2570-merge-two-2d-arrays-by-summing-values/">花花酱 2570. Merge Two 2D Arrays by Summing Values</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>2D</strong>&nbsp;integer arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2.</code></p>



<ul><li><code>nums1[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id&nbsp;<code>id<sub>i</sub></code>&nbsp;has a value equal to&nbsp;<code>val<sub>i</sub></code>.</li><li><code>nums2[i] = [id<sub>i</sub>, val<sub>i</sub>]</code>&nbsp;indicate that the number with the id&nbsp;<code>id<sub>i</sub></code>&nbsp;has a value equal to&nbsp;<code>val<sub>i</sub></code>.</li></ul>



<p>Each array contains&nbsp;<strong>unique</strong>&nbsp;ids and is sorted in&nbsp;<strong>ascending</strong>&nbsp;order by id.</p>



<p>Merge the two arrays into one array that is sorted in ascending order by id, respecting the following conditions:</p>



<ul><li>Only ids that appear in at least one of the two arrays should be included in the resulting array.</li><li>Each id should be included&nbsp;<strong>only once</strong>&nbsp;and its value should be the sum of the values of this id in the two arrays. If the id does not exist in one of the two arrays then its value in that array is considered to be&nbsp;<code>0</code>.</li></ul>



<p>Return&nbsp;<em>the resulting array</em>. The returned array must be sorted in ascending order by id.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [[1,2],[2,3],[4,5]], nums2 = [[1,4],[3,2],[4,1]]
<strong>Output:</strong> [[1,6],[2,3],[3,2],[4,6]]
<strong>Explanation:</strong> The resulting array contains the following:
- id = 1, the value of this id is 2 + 4 = 6.
- id = 2, the value of this id is 3.
- id = 3, the value of this id is 2.
- id = 4, the value of this id is 5 + 1 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [[2,4],[3,6],[5,5]], nums2 = [[1,3],[4,3]]
<strong>Output:</strong> [[1,3],[2,4],[3,6],[4,3],[5,5]]
<strong>Explanation:</strong> There are no common ids, so we just include each id with its value in the resulting list.
</pre>



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



<ul><li><code>1 &lt;= nums1.length, nums2.length &lt;= 200</code></li><li><code>nums1[i].length == nums2[j].length == 2</code></li><li><code>1 &lt;= id<sub>i</sub>, val<sub>i</sub> &lt;= 1000</code></li><li>Both arrays contain unique ids.</li><li>Both arrays are in&nbsp;strictly ascending order by id.</li></ul>



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



<p>Time complexity: O(m + 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;vector&lt;int&gt;&gt; mergeArrays(vector&lt;vector&lt;int&gt;&gt;&amp; nums1, vector&lt;vector&lt;int&gt;&gt;&amp; nums2) {
      vector&lt;vector&lt;int&gt;&gt; ans;
      for (int i = 0, j = 0; i &lt; nums1.size() || j &lt; nums2.size();) {
        const int id1 = i &lt; nums1.size() ? nums1[i][0] : INT_MAX;
        const int id2 = j &lt; nums2.size() ? nums2[j][0] : INT_MAX;
        if (id1 == id2) {
          ans.push_back({id1, nums1[i++][1] + nums2[j++][1]});
        } else if (id1 &lt; id2) {
          ans.push_back(nums1[i++]);
        } else {
          ans.push_back(nums2[j++]);
        }
      }
      return ans;
    }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/2570-merge-two-2d-arrays-by-summing-values/">花花酱 2570. Merge Two 2D Arrays by Summing Values</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/2570-merge-two-2d-arrays-by-summing-values/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2563. Count the Number of Fair Pairs</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Feb 2023 16:28:04 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pair]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9939</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums&#160;of size&#160;n&#160;and two integers&#160;lower&#160;and&#160;upper, return&#160;the number of fair pairs. A pair&#160;(i, j)&#160;is&#160;fair&#160;if: 0 &#60;= i &#60; j &#60; n, and lower &#60;= nums[i]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/">花花酱 LeetCode 2563. Count the Number of Fair Pairs</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&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;and two integers&nbsp;<code>lower</code>&nbsp;and&nbsp;<code>upper</code>, return&nbsp;<em>the number of fair pairs</em>.</p>



<p>A pair&nbsp;<code>(i, j)</code>&nbsp;is&nbsp;<strong>fair&nbsp;</strong>if:</p>



<ul><li><code>0 &lt;= i &lt; j &lt; n</code>, and</li><li><code>lower &lt;= nums[i] + nums[j] &lt;= upper</code></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,7,4,4,5], lower = 3, upper = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> There are 6 fair pairs: (0,3), (0,4), (0,5), (1,3), (1,4), and (1,5).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,7,9,2,5], lower = 11, upper = 11
<strong>Output:</strong> 1
<strong>Explanation:</strong> There is a single fair pair: (2,3).
</pre>



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



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



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



<p>Sort the array, use two pointers to find how # of pairs (i, j) s.t. nums[i] + nums[j] &lt;= limit.<br>Ans = count(upper) &#8211; count(lower &#8211; 1)</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:
  long long countFairPairs(vector&lt;int&gt;&amp; nums, int lower, int upper) {
    sort(begin(nums), end(nums));
    auto count = [&amp;](int limit) -&gt; long long {
      long long ans = 0;
      for (int i = 0, j = nums.size() - 1; i &lt; j; ++i) {
        while (i &lt; j &amp;&amp; nums[i] + nums[j] &gt; limit) --j;
        ans += j - i;
      }
      return ans;
    };
    return count(upper) - count(lower - 1);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2563-count-the-number-of-fair-pairs/">花花酱 LeetCode 2563. Count the Number of Fair Pairs</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-2563-count-the-number-of-fair-pairs/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2410. Maximum Matching of Players With Trainers</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Sep 2022 20:04:24 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9827</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;players, where&#160;players[i]&#160;represents the&#160;ability&#160;of the&#160;ith&#160;player. You are also given a&#160;0-indexed&#160;integer array&#160;trainers, where&#160;trainers[j]&#160;represents the&#160;training capacity&#160;of the&#160;jth&#160;trainer. The&#160;ith&#160;player can&#160;match&#160;with the&#160;jth&#160;trainer if the player&#8217;s ability&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/">花花酱 LeetCode 2410. Maximum Matching of Players With Trainers</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>players</code>, where&nbsp;<code>players[i]</code>&nbsp;represents the&nbsp;<strong>ability</strong>&nbsp;of the&nbsp;<code>i<sup>th</sup></code>&nbsp;player. You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>trainers</code>, where&nbsp;<code>trainers[j]</code>&nbsp;represents the&nbsp;<strong>training capacity&nbsp;</strong>of the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer.</p>



<p>The&nbsp;<code>i<sup>th</sup></code>&nbsp;player can&nbsp;<strong>match</strong>&nbsp;with the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer if the player&#8217;s ability is&nbsp;<strong>less than or equal to</strong>&nbsp;the trainer&#8217;s training capacity. Additionally, the&nbsp;<code>i<sup>th</sup></code>&nbsp;player can be matched with at most one trainer, and the&nbsp;<code>j<sup>th</sup></code>&nbsp;trainer can be matched with at most one player.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of matchings between&nbsp;</em><code>players</code><em>&nbsp;and&nbsp;</em><code>trainers</code><em>&nbsp;that satisfy these conditions.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> players = [4,7,9], trainers = [8,2,5,8]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 &lt;= 8.
- players[1] can be matched with trainers[3] since 7 &lt;= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> players = [1,1,1], trainers = [10]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
</pre>



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



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



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



<p>Sort players and trainers.</p>



<p>Loop through players, skip trainers until he/she can match the current players.</p>



<p>Time complexity: O(nlogn + mlogm + n + m)<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 matchPlayersAndTrainers(vector&lt;int&gt;&amp; players, vector&lt;int&gt;&amp; trainers) {
    sort(begin(players), end(players));
    sort(begin(trainers), end(trainers));
    const int n = players.size();
    const int m = trainers.size();
    int ans = 0;
    for (int i = 0, j = 0; i &lt; n &amp;&amp; j &lt; m; ++i) {
      while (j &lt; m &amp;&amp; players[i] &gt; trainers[j]) ++j;
      if (j++ == m) break;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2410-maximum-matching-of-players-with-trainers/">花花酱 LeetCode 2410. Maximum Matching of Players With Trainers</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-2410-maximum-matching-of-players-with-trainers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2216. Minimum Deletions to Make Array Beautiful</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2216-minimum-deletions-to-make-array-beautiful/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2216-minimum-deletions-to-make-array-beautiful/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 29 Mar 2022 03:02:37 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[remove]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9587</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums. The array&#160;nums&#160;is&#160;beautiful&#160;if: nums.length&#160;is even. nums[i] != nums[i + 1]&#160;for all&#160;i % 2 == 0. Note that an empty array is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2216-minimum-deletions-to-make-array-beautiful/">花花酱 LeetCode 2216. Minimum Deletions to Make Array Beautiful</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. The array&nbsp;<code>nums</code>&nbsp;is&nbsp;<strong>beautiful</strong>&nbsp;if:</p>



<ul><li><code>nums.length</code>&nbsp;is even.</li><li><code>nums[i] != nums[i + 1]</code>&nbsp;for all&nbsp;<code>i % 2 == 0</code>.</li></ul>



<p>Note that an empty array is considered beautiful.</p>



<p>You can delete any number of elements from&nbsp;<code>nums</code>. When you delete an element, all the elements to the right of the deleted element will be&nbsp;<strong>shifted one unit to the left</strong>&nbsp;to fill the gap created and all the elements to the left of the deleted element will remain&nbsp;<strong>unchanged</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of elements to delete from&nbsp;</em><code>nums</code><em>&nbsp;to make it&nbsp;</em><em>beautiful.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,2,3,5]
<strong>Output:</strong> 1
<strong>Explanation:</strong> You can delete either <code>nums[0]</code> or <code>nums[1]</code> to make <code>nums</code> = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make <code>nums</code> beautiful.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,2,2,3,3]
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can delete <code>nums[0]</code> and <code>nums[5]</code> to make nums = [1,2,2,3] which is beautiful. It can be proven you need at least 2 deletions to make nums beautiful.
</pre>



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



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



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



<p>If two consecutive numbers are the same, we must remove one. We don&#8217;t need to actually remove elements from array, just need to track how many elements have been removed so far.</p>



<p>i is the position in the original array, ans is the number of elements been removed. i &#8211; ans is the position in the updated array.</p>



<p>ans += nums[i &#8211; ans] == nums[i &#8211; ans + 1]</p>



<p>Remove the last element (just increase answer by 1) if the length of the new array is odd.</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 minDeletion(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int ans = 0;
    for (int i = 0; i - ans + 1 &lt; n; i += 2)
      ans += nums[i - ans] == nums[i - ans + 1];
    ans += (n - ans) &amp; 1;
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2216-minimum-deletions-to-make-array-beautiful/">花花酱 LeetCode 2216. Minimum Deletions to Make Array Beautiful</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-2216-minimum-deletions-to-make-array-beautiful/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2149. Rearrange Array Elements by Sign</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2149-rearrange-array-elements-by-sign/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2149-rearrange-array-elements-by-sign/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Feb 2022 01:01:40 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[rearrange]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9470</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;of&#160;even&#160;length consisting of an&#160;equal&#160;number of positive and negative integers. You should&#160;rearrange&#160;the elements of&#160;nums&#160;such that the modified array follows the given conditions:&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2149-rearrange-array-elements-by-sign/">花花酱 LeetCode 2149. Rearrange Array Elements by Sign</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of&nbsp;<strong>even</strong>&nbsp;length consisting of an&nbsp;<strong>equal</strong>&nbsp;number of positive and negative integers.</p>



<p>You should&nbsp;<strong>rearrange</strong>&nbsp;the elements of&nbsp;<code>nums</code>&nbsp;such that the modified array follows the given conditions:</p>



<ol><li>Every&nbsp;<strong>consecutive pair</strong>&nbsp;of integers have&nbsp;<strong>opposite signs</strong>.</li><li>For all integers with the same sign, the&nbsp;<strong>order</strong>&nbsp;in which they were present in&nbsp;<code>nums</code>&nbsp;is&nbsp;<strong>preserved</strong>.</li><li>The rearranged array begins with a positive integer.</li></ol>



<p>Return&nbsp;<em>the modified array after rearranging the elements to satisfy the aforementioned conditions</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,1,-2,-5,2,-4]
<strong>Output:</strong> [3,-2,1,-5,2,-4]
<strong>Explanation:</strong>
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,1]
<strong>Output:</strong> [1,-1]
<strong>Explanation:</strong>
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to [1,-1].
</pre>



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



<ul><li><code>2 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li><li><code>nums.length</code>&nbsp;is&nbsp;<strong>even</strong></li><li><code>1 &lt;= |nums[i]| &lt;= 10<sup>5</sup></code></li><li><code>nums</code>&nbsp;consists of&nbsp;<strong>equal</strong>&nbsp;number of positive and negative integers.</li></ul>



<h2><strong>Solution 1: Split and merge</strong></h2>



<p>Create two arrays to store positive and negative numbers.</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:
  vector&lt;int&gt; rearrangeArray(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; pos;
    vector&lt;int&gt; neg;
    for (int x : nums)
      (x &gt; 0 ? pos : neg).push_back(x);
    vector&lt;int&gt; ans;
    for (int i = 0; i &lt; pos.size(); ++i) {
      ans.push_back(pos[i]);
      ans.push_back(neg[i]);
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Two Pointers</strong></h2>



<p>Use two pointers to store the next pos / neg.</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:
  vector&lt;int&gt; rearrangeArray(vector&lt;int&gt;&amp; nums) {
    vector&lt;int&gt; ans(nums.size());    
    int pos = 0;
    int neg = 1;
    for (int x : nums) {
      int&amp; index = x &gt; 0 ? pos : neg;
      ans[index] = x;
      index += 2;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2149-rearrange-array-elements-by-sign/">花花酱 LeetCode 2149. Rearrange Array Elements by Sign</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-2149-rearrange-array-elements-by-sign/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2105. Watering Plants II</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2105-watering-plants-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2105-watering-plants-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 13 Dec 2021 01:52:00 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9168</guid>

					<description><![CDATA[<p>Problem Solution: Simulation w/ Two Pointers Simulate the watering process. Time complexity: O(n)Space complexity: O(1) [crayon-663cae9a0ca97758916026/]</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2105-watering-plants-ii/">花花酱 LeetCode 2105. Watering Plants II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2><strong><a href="https://leetcode.com/problems/watering-plants-ii/">Problem</a></strong></h2>



<p>Solution: Simulation w/ Two Pointers</p>



<p>Simulate the watering process.</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 minimumRefill(vector&lt;int&gt;&amp; plants, int capacityA, int capacityB) {
    const int n = plants.size();    
    int ans = 0;
    for (int l = 0, r = n - 1, A = capacityA, B = capacityB; l &lt;= r; ++l, --r) {      
      if (l == r)
        return ans += max(A, B) &lt; plants[l];
      if ((A -= plants[l]) &lt; 0) 
        A = capacityA - plants[l], ++ans;        
      if ((B -= plants[r]) &lt; 0) 
        B = capacityB - plants[r], ++ans;     
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-2105-watering-plants-ii/">花花酱 LeetCode 2105. Watering Plants II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-2105-watering-plants-ii/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 1855. Maximum Distance Between a Pair of Values</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1855-maximum-distance-between-a-pair-of-values/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1855-maximum-distance-between-a-pair-of-values/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 May 2021 06:48:26 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8447</guid>

					<description><![CDATA[<p>You are given two&#160;non-increasing 0-indexed&#160;integer arrays&#160;nums1​​​​​​ and&#160;nums2​​​​​​. A pair of indices&#160;(i, j), where&#160;0 &#60;= i &#60; nums1.length&#160;and&#160;0 &#60;= j &#60; nums2.length, is&#160;valid&#160;if both&#160;i &#60;= j&#160;and&#160;nums1[i]&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1855-maximum-distance-between-a-pair-of-values/">花花酱 LeetCode 1855. Maximum Distance Between a Pair of Values</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>non-increasing 0-indexed&nbsp;</strong>integer arrays&nbsp;<code>nums1</code>​​​​​​ and&nbsp;<code>nums2</code>​​​​​​.</p>



<p>A pair of indices&nbsp;<code>(i, j)</code>, where&nbsp;<code>0 &lt;= i &lt; nums1.length</code>&nbsp;and&nbsp;<code>0 &lt;= j &lt; nums2.length</code>, is&nbsp;<strong>valid</strong>&nbsp;if both&nbsp;<code>i &lt;= j</code>&nbsp;and&nbsp;<code>nums1[i] &lt;= nums2[j]</code>. The&nbsp;<strong>distance</strong>&nbsp;of the pair is&nbsp;<code>j - i</code>​​​​.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum distance</strong>&nbsp;of any&nbsp;<strong>valid</strong>&nbsp;pair&nbsp;</em><code>(i, j)</code><em>. If there are no valid pairs, return&nbsp;</em><code>0</code>.</p>



<p>An array&nbsp;<code>arr</code>&nbsp;is&nbsp;<strong>non-increasing</strong>&nbsp;if&nbsp;<code>arr[i-1] &gt;= arr[i]</code>&nbsp;for every&nbsp;<code>1 &lt;= i &lt; arr.length</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [2,2,2], nums2 = [10,10,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]
<strong>Output:</strong> 2
<strong>Explanation:</strong> The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [5,4], nums2 = [3,2]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no valid pairs, so return 0.
</pre>



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



<ul><li><code>1 &lt;= nums1.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums2.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums1[i], nums2[j] &lt;= 10<sup>5</sup></code></li><li>Both&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>&nbsp;are&nbsp;<strong>non-increasing</strong>.</li></ul>



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



<p>For each i, find the largest j such that nums[j] &gt;= nums[i].</p>



<p>Time complexity: O(n + m)<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 maxDistance(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {    
    int ans = 0;
    for (int i = 0, j = -1; i &lt; nums1.size(); ++i) {
      while (j + 1 &lt; nums2.size() &amp;&amp; nums2[j + 1] &gt;= nums1[i]) ++j;
      if (j &gt;= i) ans = max(ans, j - i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1855-maximum-distance-between-a-pair-of-values/">花花酱 LeetCode 1855. Maximum Distance Between a Pair of Values</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-1855-maximum-distance-between-a-pair-of-values/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1793. Maximum Score of a Good Subarray</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1793-maximum-score-of-a-good-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1793-maximum-score-of-a-good-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 19 Mar 2021 02:13:15 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8245</guid>

					<description><![CDATA[<p>You are given an array of integers&#160;nums&#160;(0-indexed)&#160;and an integer&#160;k. The&#160;score&#160;of a subarray&#160;(i, j)&#160;is defined as&#160;min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1). A&#160;good&#160;subarray&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1793-maximum-score-of-a-good-subarray/">花花酱 LeetCode 1793. Maximum Score of a Good 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 array of integers&nbsp;<code>nums</code>&nbsp;<strong>(0-indexed)</strong>&nbsp;and an integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>score</strong>&nbsp;of a subarray&nbsp;<code>(i, j)</code>&nbsp;is defined as&nbsp;<code>min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)</code>. A&nbsp;<strong>good</strong>&nbsp;subarray is a subarray where&nbsp;<code>i &lt;= k &lt;= j</code>.</p>



<p>Return&nbsp;<em>the maximum possible&nbsp;<strong>score</strong>&nbsp;of a&nbsp;<strong>good</strong>&nbsp;subarray.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,3,7,4,5], k = 3
<strong>Output:</strong> 15
<strong>Explanation:</strong> The optimal subarray is (1, 5) with a score of min(4,3,7,4,5) * (5-1+1) = 3 * 5 = 15. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,5,4,5,4,1,1,1], k = 0
<strong>Output:</strong> 20
<strong>Explanation:</strong> The optimal subarray is (0, 4) with a score of min(5,5,4,5,4) * (4-0+1) = 4 * 5 = 20.
</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;= 2 * 10<sup>4</sup></code></li><li><code>0 &lt;= k &lt; nums.length</code></li></ul>



<h2><strong>Solutions: Two Pointers</strong></h2>



<p>maintain a window [i, j],  m = min(nums[i~j]), expend to the left if nums[i &#8211; 1] &gt;= nums[j + 1], otherwise expend to the right. </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 maximumScore(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();    
    int ans = 0;
    for (int i = k, j = k, m = nums[k];;) {
      ans = max(ans, m * (j - i + 1));      
      if (j - i + 1 == n) break;
      int l = i ? nums[i - 1] : -1;
      int r = j + 1 &lt; n ? nums[j + 1] : -1;
      if (l &gt;= r)
        m = min(m, nums[--i]);
      else
        m = min(m, nums[++j]);      
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1793-maximum-score-of-a-good-subarray/">花花酱 LeetCode 1793. Maximum Score of a Good 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/two-pointers/leetcode-1793-maximum-score-of-a-good-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1574-shortest-subarray-to-be-removed-to-make-array-sorted/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1574-shortest-subarray-to-be-removed-to-make-array-sorted/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Sep 2020 00:36:24 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[descending]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7338</guid>

					<description><![CDATA[<p>Given an integer array&#160;arr, remove a&#160;subarray (can be empty) from&#160;arr&#160;such that the remaining elements in&#160;arr&#160;are&#160;non-decreasing. A subarray is a contiguous&#160;subsequence of the array. Return&#160;the length&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1574-shortest-subarray-to-be-removed-to-make-array-sorted/">花花酱 LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted</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>arr</code>, remove a&nbsp;subarray (can be empty) from&nbsp;<code>arr</code>&nbsp;such that the remaining elements in&nbsp;<code>arr</code>&nbsp;are&nbsp;<strong>non-decreasing</strong>.</p>



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



<p>Return&nbsp;<em>the length of the shortest subarray to remove</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3,10,4,2,3,5]
<strong>Output:</strong> 3
<strong>Explanation: </strong>The shortest subarray we can remove is [10,4,2] of length 3. The remaining elements after that will be [1,2,3,3,5] which are sorted.
Another correct solution is to remove the subarray [3,10,4].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [5,4,3,2,1]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Since the array is strictly decreasing, we can only keep a single element. Therefore we need to remove a subarray of length 4, either [5,4,3,2] or [4,3,2,1].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,2,3]
<strong>Output:</strong> 0
<strong>Explanation: </strong>The array is already non-decreasing. We do not need to remove any elements.
</pre>



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



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



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



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



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



<p>Find the right most j such that arr[j &#8211; 1] &gt; arr[j], if not found which means the entire array is sorted return 0. Then we have a non-descending subarray arr[j~n-1].<br><br>We maintain two pointers i, j, such that arr[0~i] is non-descending and arr[i] &lt;= arr[j] which means we can remove arr[i+1~j-1] to get a non-descending array. Number of elements to remove is j &#8211; i &#8211; 1 .</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 findLengthOfShortestSubarray(vector&lt;int&gt;&amp; arr) {
    const int n = arr.size();
    int j = n - 1;
    while (j &gt; 0 &amp;&amp; arr[j - 1] &lt;= arr[j]) --j;
    if (j == 0) return 0;
    int ans = j; // remove arr[0~j-1]
    for (int i = 0; i &lt; n; ++i) {
      if (i &gt; 0 &amp;&amp; arr[i - 1] &gt; arr[i]) break;
      while (j &lt; n &amp;&amp; arr[i] &gt; arr[j]) ++j;      
      // arr[i] &lt;= arr[j], remove arr[i + 1 ~ j - 1]
      ans = min(ans, j - i - 1);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1574-shortest-subarray-to-be-removed-to-make-array-sorted/">花花酱 LeetCode 1574. Shortest Subarray to be Removed to Make Array Sorted</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-1574-shortest-subarray-to-be-removed-to-make-array-sorted/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1537. Get the Maximum Score</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1537-get-the-maximum-score/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1537-get-the-maximum-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 02 Aug 2020 19:52:45 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[two poiners]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7197</guid>

					<description><![CDATA[<p>You are given two&#160;sorted&#160;arrays of distinct integers&#160;nums1&#160;and&#160;nums2. A&#160;validpath&#160;is defined as follows: Choose&#160;array nums1 or nums2 to traverse (from index-0). Traverse the current array from left&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1537-get-the-maximum-score/">花花酱 LeetCode 1537. Get the Maximum Score</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given two&nbsp;<strong>sorted</strong>&nbsp;arrays of distinct integers&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2.</code></p>



<p>A&nbsp;<strong>validpath</strong>&nbsp;is defined as follows:</p>



<ul><li>Choose&nbsp;array nums1 or nums2 to traverse (from index-0).</li><li>Traverse the current array from left to right.</li><li>If you are reading any value that is present in&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>&nbsp;you are allowed to change your path to the other array. (Only one repeated value is considered in the&nbsp;valid path).</li></ul>



<p><em>Score</em>&nbsp;is defined as the sum of uniques values in a valid path.</p>



<p>Return the maximum&nbsp;<em>score</em>&nbsp;you can obtain of all possible&nbsp;<strong>valid&nbsp;paths</strong>.</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>



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2020/07/16/sample_1_1893.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [2,4,5,8,10], nums2 = [4,6,8,9]
<strong>Output:</strong> 30
<strong>Explanation:</strong>&nbsp;Valid paths:
[2,4,5,8,10], [2,4,5,8,9], [2,4,6,8,9], [2,4,6,8,10],  (starting from nums1)
[4,6,8,9], [4,5,8,10], [4,5,8,9], [4,6,8,10]    (starting from nums2)
The maximum is obtained with the path in green <strong>[2,4,6,8,10]</strong>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,3,5,7,9], nums2 = [3,5,100]
<strong>Output:</strong> 109
<strong>Explanation:</strong>&nbsp;Maximum sum is obtained with the path <strong>[1,3,5,100]</strong>.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10]
<strong>Output:</strong> 40
<strong>Explanation:</strong>&nbsp;There are no common elements between nums1 and nums2.
Maximum sum is obtained with the path [6,7,8,9,10].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,4,5,8,9,11,19], nums2 = [2,3,4,11,12]
<strong>Output:</strong> 61
</pre>



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



<ul><li><code>1 &lt;= nums1.length &lt;= 10^5</code></li><li><code>1 &lt;= nums2.length &lt;= 10^5</code></li><li><code>1 &lt;= nums1[i], nums2[i] &lt;= 10^7</code></li><li><code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>&nbsp;are strictly increasing.</li></ul>



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



<p>Since numbers are strictly increasing, we can always traverse the smaller one using two pointers. <br>Traversing ([2,4,5,8,10], [4,6,8,10])<br>will be like [2, 4/4, 5, 6, 8, 10/10]<br>It two nodes have the same value, we have two choices and pick the larger one, then both move nodes one step forward. Otherwise, the smaller node moves one step forward.<br>dp1[i] := max path sum ends with nums1[i-1]<br>dp2[j] := max path sum ends with nums2[j-1]<br>if nums[i -1] == nums[j &#8211; 1]:<br>  dp1[i] = dp2[j] = max(dp[i-1], dp[j-1]) + nums[i -1]<br>  i += 1, j += 1<br>else if nums[i &#8211; 1] &lt; nums[j &#8211; 1]:<br>  dp[i] = dp[i-1] + nums[i -1]<br>  i += 1<br>else if nums[j &#8211; 1] &lt; nums[i &#8211; 1]:<br>  dp[j] = dp[j-1] + nums[j -1]<br>  j += 1<br>return max(dp1[-1], dp2[-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">class Solution {
public:
  int maxSum(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    constexpr int kMod = 1e9 + 7;
    const int n1 = nums1.size();
    const int n2 = nums2.size();
    vector&lt;long&gt; dp1(n1 + 1); // max path sum ends with nums1[i-1]
    vector&lt;long&gt; dp2(n2 + 1); // max path sum ends with nums2[j-1]
    int i = 0;
    int j = 0;
    while (i &lt; n1 || j &lt; n2) {
      if (i &lt; n1 &amp;&amp; j &lt; n2 &amp;&amp; nums1[i] == nums2[j]) {
        // Same, two choices, pick the larger one.
        dp2[j + 1] = dp1[i + 1] = max(dp1[i], dp2[j]) + nums1[i];
        ++i; ++j;
      } else if (i &lt; n1 &amp;&amp; (j == n2 || nums1[i] &lt; nums2[j])) {
        dp1[i + 1] = dp1[i] + nums1[i];
        ++i;
      } else if (j &lt; n2 &amp;&amp; (i == n1 || nums2[j] &lt; nums1[i])) {        
        dp2[j + 1] = dp2[j] + nums2[j];
        ++j;
      }
    }    
    return max(dp1.back(), dp2.back()) % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution {
  public int maxSum(int[] nums1, int[] nums2) {
    final int kMod = 1_000_000_007;
    int n1 = nums1.length;
    int n2 = nums2.length;
    int i = 0;
    int j = 0;
    long a = 0;
    long b = 0;
    while (i &lt; n1 || j &lt; n2) {
      if (i &lt; n1 &amp;&amp; j &lt; n2 &amp;&amp; nums1[i] == nums2[j]) {
        a = b = Math.max(a, b) + nums1[i];
        ++i;
        ++j;
      } else if (i &lt; n1 &amp;&amp; (j == n2 || nums1[i] &lt; nums2[j])) {
        a += nums1[i++];        
      } else {
        b += nums2[j++];
      }
    }
    return (int)(Math.max(a, b) % kMod);
  }
}</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def maxSum(self, nums1: List[int], nums2: List[int]) -&gt; int:
    n1, n2 = len(nums1), len(nums2)
    i, j = 0, 0
    a, b = 0, 0
    while i &lt; n1 or j &lt; n2:
      if i &lt; n1 and j &lt; n2 and nums1[i] == nums2[j]:
        a = b = max(a, b) + nums1[i]
        i += 1
        j += 1
      elif i &lt; n1 and (j == n2 or nums1[i] &lt; nums2[j]):
        a += nums1[i]
        i += 1
      else:
        b += nums2[j]
        j += 1
    return max(a, b) % (10**9 + 7)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1537-get-the-maximum-score/">花花酱 LeetCode 1537. Get the Maximum Score</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-1537-get-the-maximum-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1498-number-of-subsequences-that-satisfy-the-given-sum-condition/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1498-number-of-subsequences-that-satisfy-the-given-sum-condition/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Jun 2020 08:25:06 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[two pointers]]></category>
		<category><![CDATA[two sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6999</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums&#160;and an integer&#160;target. Return the number of&#160;non-empty&#160;subsequences of&#160;nums&#160;such that the sum of the minimum and maximum element on it is less&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1498-number-of-subsequences-that-satisfy-the-given-sum-condition/">花花酱 LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition</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>nums</code>&nbsp;and an integer&nbsp;<code>target</code>.</p>



<p>Return the number of&nbsp;<strong>non-empty</strong>&nbsp;subsequences of&nbsp;<code>nums</code>&nbsp;such that the sum of the minimum and maximum element on it is less or equal than&nbsp;<code>target</code>.</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> nums = [3,5,6,7], target = 9
<strong>Output:</strong> 4
<strong>Explanation: </strong>There are 4 subsequences that satisfy the condition.
[3] -&gt; Min value + max value &lt;= target (3 + 3 &lt;= 9)
[3,5] -&gt; (3 + 5 &lt;= 9)
[3,5,6] -&gt; (3 + 6 &lt;= 9)
[3,6] -&gt; (3 + 6 &lt;= 9)
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,3,6,8], target = 10
<strong>Output:</strong> 6
<strong>Explanation: </strong>There are 6 subsequences that satisfy the condition. (nums can have repeated numbers).
[3] , [3] , [3,3], [3,6] , [3,6] , [3,3,6]</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,3,4,6,7], target = 12
<strong>Output:</strong> 61
<strong>Explanation: </strong>There are 63 non-empty subsequences, two of them don't satisfy the condition ([6,7], [7]).
Number of valid subsequences (63 - 2 = 61).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,2,4,1,7,6,8], target = 16
<strong>Output:</strong> 127
<strong>Explanation: </strong>All non-empty subset satisfy the condition (2^7 - 1) = 127</pre>



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



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



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



<p>Since order of the elements in the subsequence doesn&#8217;t matter, we can sort the input array.<br>Very similar to two sum, we use two pointers (i, j) to maintain a window, s.t. nums[i] +nums[j] &lt;= target.<br>Then fix nums[i], any subset of (nums[i+1~j]) gives us a valid subsequence, thus we have 2^(j-(i+1)+1) = 2^(j-i) valid subsequence for window (i, j).</p>



<p>Time complexity: O(nlogn) // Sort<br>Space complexity: O(n) // need to precompute 2^n % kMod.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int numSubseq(vector&lt;int&gt;&amp; nums, int target) {
    constexpr int kMod = 1e9 + 7;
    const int n = nums.size();
    vector&lt;int&gt; p(n + 1, 1);
    for (int i = 1; i &lt;= n; ++i) 
      p[i] = (p[i - 1] &lt;&lt; 1) % kMod;
    sort(begin(nums), end(nums));
    int ans = 0;
    for (int i = 0, j = n - 1; i &lt;= j; ++i) {
      while (i &lt;= j &amp;&amp; nums[i] + nums[j] &gt; target) --j;
      if (i &gt; j) continue;
      // In subarray nums[i~j]:
      // min = nums[i], max = nums[j]
      // nums[i] + nums[j] &lt;= target
      // {nums[i], (j - i - 1 + 1 values)}
      // Any subset of the right part gives a valid subsequence 
      // in the original array. And There are 2^(j - i) ones.
      ans = (ans + p[j - i]) % kMod;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1498-number-of-subsequences-that-satisfy-the-given-sum-condition/">花花酱 LeetCode 1498. Number of Subsequences That Satisfy the Given Sum Condition</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-1498-number-of-subsequences-that-satisfy-the-given-sum-condition/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1385. Find the Distance Value Between Two Arrays</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1385-find-the-distance-value-between-two-arrays/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-1385-find-the-distance-value-between-two-arrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 21 Mar 2020 23:20:50 +0000</pubDate>
				<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6517</guid>

					<description><![CDATA[<p>Given two integer arrays&#160;arr1&#160;and&#160;arr2, and the integer&#160;d,&#160;return the distance value between the two&#160;arrays. The distance value is defined as the number of elements&#160;arr1[i]&#160;such that there&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1385-find-the-distance-value-between-two-arrays/">花花酱 LeetCode 1385. Find the Distance Value Between Two Arrays</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 integer arrays&nbsp;<code>arr1</code>&nbsp;and&nbsp;<code>arr2</code>, and the integer&nbsp;<code>d</code>,&nbsp;<em>return the distance value between the two&nbsp;arrays</em>.</p>



<p>The distance value is defined as the number of elements&nbsp;<code>arr1[i]</code>&nbsp;such that there is not any element&nbsp;<code>arr2[j]</code>&nbsp;where&nbsp;<code>|arr1[i]-arr2[j]| &lt;= d</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [4,5,8], arr2 = [10,9,1,8], d = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
For arr1[0]=4 we have: 
|4-10|=6 &gt; d=2 
|4-9|=5 &gt; d=2 
|4-1|=3 &gt; d=2 
|4-8|=4 &gt; d=2 
For arr1[1]=5 we have: 
|5-10|=5 &gt; d=2 
|5-9|=4 &gt; d=2 
|5-1|=4 &gt; d=2 
|5-8|=3 &gt; d=2
For arr1[2]=8 we have:
<strong>|8-10|=2 &lt;= d=2</strong>
<strong>|8-9|=1 &lt;= d=2</strong>
|8-1|=7 &gt; d=2
<strong>|8-8|=0 &lt;= d=2</strong>
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [1,4,2,3], arr2 = [-4,-3,6,10,20,30], d = 3
<strong>Output:</strong> 2
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr1 = [2,1,100,3], arr2 = [-5,-2,10,-3,7], d = 6
<strong>Output:</strong> 1
</pre>



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



<ul><li><code>1 &lt;= arr1.length, arr2.length &lt;= 500</code></li><li><code>-10^3 &lt;= arr1[i], arr2[j] &lt;= 10^3</code></li><li><code>0 &lt;= d &lt;= 100</code></li></ul>



<h2><strong>Solution 1:  All pairs</strong></h2>



<p>Time complexity: O(m*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 findTheDistanceValue(vector&lt;int&gt;&amp; arr1, vector&lt;int&gt;&amp; arr2, int d) {    
    int ans = 0;
    for (int x : arr1) {
      bool flag = true;
      for (int y : arr2)
        if (abs(x - y) &lt;= d) {
          flag = false;
          break;
        }
      ans += flag;
    }
    return ans;
  }
};</pre>
</div></div>



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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def findTheDistanceValue(self, arr1: List[int], arr2: List[int], d: int) -&gt; int:
    return sum(all(abs(x - y) &gt; d for y in arr2) for x in arr1)</pre>
</div></div>



<h2><strong>Solution 2: Two Pointers</strong></h2>



<p>Sort arr1 in ascending order and sort arr2 in descending order.<br>Time complexity: O(mlogm + nlogn + m + 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 findTheDistanceValue(vector&lt;int&gt;&amp; arr1, vector&lt;int&gt;&amp; arr2, int d) {    
    sort(begin(arr1), end(arr1));
    sort(rbegin(arr2), rend(arr2));
    int ans = 0;
    for (int a : arr1) {
      while (arr2.size() &amp;&amp; arr2.back() &lt; a - d)
        arr2.pop_back();
      ans += arr2.empty() || arr2.back() &gt; a + d;
    }
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 3: Binary Search</strong></h2>



<p>Sort arr2 in ascending order. and do two binary searches for each element to determine the range of [a-d, a+d], if that range is empty we increase the counter</p>



<p>Time complexity: O(mlogm + nlogm)<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 findTheDistanceValue(vector&lt;int&gt;&amp; arr1, vector&lt;int&gt;&amp; arr2, int d) {    
    sort(begin(arr2), end(arr2));
    int ans = 0;
    for (int a : arr1) {
      auto it1 = lower_bound(begin(arr2), end(arr2), a - d);
      auto it2 = upper_bound(begin(arr2), end(arr2), a + d);
      if (it1 == it2) ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-1385-find-the-distance-value-between-two-arrays/">花花酱 LeetCode 1385. Find the Distance Value Between Two Arrays</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-1385-find-the-distance-value-between-two-arrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 240. Search a 2D Matrix II</title>
		<link>https://zxi.mytechroad.com/blog/two-pointers/leetcode-240-search-a-2d-matrix-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/two-pointers/leetcode-240-search-a-2d-matrix-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Mar 2020 06:35:32 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Two pointers]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6474</guid>

					<description><![CDATA[<p>Write an efficient algorithm that searches for a value in an&#160;m&#160;x&#160;n&#160;matrix. This matrix has the following properties: Integers in each row are sorted in ascending&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-240-search-a-2d-matrix-ii/">花花酱 LeetCode 240. Search a 2D Matrix II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Write an efficient algorithm that searches for a value in an&nbsp;<em>m</em>&nbsp;x&nbsp;<em>n</em>&nbsp;matrix. This matrix has the following properties:</p>



<ul><li>Integers in each row are sorted in ascending from left to right.</li><li>Integers in each column are sorted in ascending from top to bottom.</li></ul>



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



<p>Consider the following matrix:</p>



<pre class="wp-block-preformatted;crayon:false">[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]
</pre>



<p>Given&nbsp;target&nbsp;=&nbsp;<code>5</code>, return&nbsp;<code>true</code>.</p>



<h2><strong>Solution 1: Two Pointers</strong></h2>



<p>Start from first row + last column, if the current value is larger than target, &#8211;column; if smaller then ++row.</p>



<p>e.g. <br>1. r = 0, c = 4, v = 15, 15 &gt; 5 =&gt; &#8211;c<br>2. r = 0, c = 3, v = 11, 11 &gt; 5 =&gt; &#8211;c<br>3. r = 0, c = 2, v = 7, 7 &gt; 5 =&gt; &#8211;c<br>4. r = 0, c = 1, v = 4, 4 &lt; 5 =&gt; ++r<br>5. r = 1, c = 1, v = 5, 5 = 5, found it!</p>



<p>Time complexity: O(m + 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:
  bool searchMatrix(vector&lt;vector&lt;int&gt;&gt;&amp; matrix, int target) {
    if (matrix.empty() || matrix[0].empty()) return false;
    const int m = matrix.size();
    const int n = matrix[0].size();
    int r = 0;
    int c = matrix[0].size() - 1;
    while (r &lt; m &amp;&amp; c &gt;= 0) {
      if (matrix[r][c] == target) return true;
      else if (matrix[r][c] &gt; target) --c;
      else ++r;
    }
    return false;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/two-pointers/leetcode-240-search-a-2d-matrix-ii/">花花酱 LeetCode 240. Search a 2D Matrix II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/two-pointers/leetcode-240-search-a-2d-matrix-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
