<?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/tag/two-pointers/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/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/tag/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>花花酱 LeetCode 2824. Count Pairs Whose Sum is Less than Target</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2824-count-pairs-whose-sum-is-less-than-target/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2824-count-pairs-whose-sum-is-less-than-target/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 24 Aug 2023 01:09:34 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10070</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums&#160;of length&#160;n&#160;and an integer&#160;target, return&#160;the number of pairs(i, j)where0 &#60;= i &#60; j &#60; nandnums[i] + nums[j] &#60; target. Example 1: Input: nums&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2824-count-pairs-whose-sum-is-less-than-target/">花花酱 LeetCode 2824. Count Pairs Whose Sum is Less than 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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;and an integer&nbsp;<code>target</code>, return&nbsp;<em>the number of pairs</em><code>(i, j)</code><em>where</em><code>0 &lt;= i &lt; j &lt; n</code><em>and</em><code>nums[i] + nums[j] &lt; target</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,1,2,3,1], target = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are 3 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 &lt; 1 and nums[0] + nums[1] = 0 &lt; target
- (0, 2) since 0 &lt; 2 and nums[0] + nums[2] = 1 &lt; target 
- (0, 4) since 0 &lt; 4 and nums[0] + nums[4] = 0 &lt; target
Note that (0, 3) is not counted since nums[0] + nums[3] is not strictly less than the target.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-6,2,5,-2,-7,-1,3], target = -2
<strong>Output:</strong> 10
<strong>Explanation:</strong> There are 10 pairs of indices that satisfy the conditions in the statement:
- (0, 1) since 0 &lt; 1 and nums[0] + nums[1] = -4 &lt; target
- (0, 3) since 0 &lt; 3 and nums[0] + nums[3] = -8 &lt; target
- (0, 4) since 0 &lt; 4 and nums[0] + nums[4] = -13 &lt; target
- (0, 5) since 0 &lt; 5 and nums[0] + nums[5] = -7 &lt; target
- (0, 6) since 0 &lt; 6 and nums[0] + nums[6] = -3 &lt; target
- (1, 4) since 1 &lt; 4 and nums[1] + nums[4] = -5 &lt; target
- (3, 4) since 3 &lt; 4 and nums[3] + nums[4] = -9 &lt; target
- (3, 5) since 3 &lt; 5 and nums[3] + nums[5] = -3 &lt; target
- (4, 5) since 4 &lt; 5 and nums[4] + nums[5] = -8 &lt; target
- (4, 6) since 4 &lt; 6 and nums[4] + nums[6] = -4 &lt; target
</pre>



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



<ul><li><code>1 &lt;= nums.length == n &lt;= 50</code></li><li><code>-50 &lt;= nums[i], target &lt;= 50</code></li></ul>



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



<p>Enumerate all pairs.</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:
  int countPairs(vector&lt;int&gt;&amp; nums, int target) {
    const int n = nums.size();
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int j = i + 1; j &lt; n; ++j)
        ans += nums[i] + nums[j] &lt; target;
    return ans;
  }
};</pre>
</div></div>



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



<p>Sort the numbers.</p>



<p>Use two pointers i, and j.<br>Set i to 0 and j to n &#8211; 1.<br>while (nums[i] + nums[j] >= target) &#8211;j<br>then we have nums[i] + nums[k] &lt; target (i &lt; k &lt;= j), in total (j &#8211; i) pairs.<br>++i, move to the next starting number.<br>Time complexity: O(nlogn + 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 countPairs(vector&lt;int&gt;&amp; nums, int target) {
    const int n = nums.size();
    sort(begin(nums), end(nums));
    int ans = 0;
    for (int i = 0, j = n - 1; i &lt; n; ++i) {
      while (j &gt;= i &amp;&amp; nums[i] + nums[j] &gt;= target) --j;      
      ans += max(0, j - i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2824-count-pairs-whose-sum-is-less-than-target/">花花酱 LeetCode 2824. Count Pairs Whose Sum is Less than 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/algorithms/array/leetcode-2824-count-pairs-whose-sum-is-less-than-target/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 2130. Maximum Twin Sum of a Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 09 Jan 2022 11:40:22 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9415</guid>

					<description><![CDATA[<p>In a linked list of size&#160;n, where&#160;n&#160;is&#160;even, the&#160;ith&#160;node (0-indexed) of the linked list is known as the&#160;twin&#160;of the&#160;(n-1-i)th&#160;node, if&#160;0 &#60;= i &#60;= (n / 2)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/">花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</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>In a linked list of size&nbsp;<code>n</code>, where&nbsp;<code>n</code>&nbsp;is&nbsp;<strong>even</strong>, the&nbsp;<code>i<sup>th</sup></code>&nbsp;node (<strong>0-indexed</strong>) of the linked list is known as the&nbsp;<strong>twin</strong>&nbsp;of the&nbsp;<code>(n-1-i)<sup>th</sup></code>&nbsp;node, if&nbsp;<code>0 &lt;= i &lt;= (n / 2) - 1</code>.</p>



<ul><li>For example, if&nbsp;<code>n = 4</code>, then node&nbsp;<code>0</code>&nbsp;is the twin of node&nbsp;<code>3</code>, and node&nbsp;<code>1</code>&nbsp;is the twin of node&nbsp;<code>2</code>. These are the only nodes with twins for&nbsp;<code>n = 4</code>.</li></ul>



<p>The&nbsp;<strong>twin sum&nbsp;</strong>is defined as the sum of a node and its twin.</p>



<p>Given the&nbsp;<code>head</code>&nbsp;of a linked list with even length, return&nbsp;<em>the&nbsp;<strong>maximum twin sum</strong>&nbsp;of the linked list</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg1drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [5,4,2,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong>
Nodes 0 and 1 are the twins of nodes 3 and 2, respectively. All have twin sum = 6.
There are no other nodes with twins in the linked list.
Thus, the maximum twin sum of the linked list is 6. 
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg2drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [4,2,2,3]
<strong>Output:</strong> 7
<strong>Explanation:</strong>
The nodes with twins present in this linked list are:
- Node 0 is the twin of node 3 having a twin sum of 4 + 3 = 7.
- Node 1 is the twin of node 2 having a twin sum of 2 + 2 = 4.
Thus, the maximum twin sum of the linked list is max(7, 4) = 7. 
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/12/03/eg3drawio.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,100000]
<strong>Output:</strong> 100001
<strong>Explanation:</strong>
There is only one node with a twin in the linked list having twin sum of 1 + 100000 = 100001.
</pre>



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



<ul><li>The number of nodes in the list is an&nbsp;<strong>even</strong>&nbsp;integer in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Two Pointers + Reverse List</strong></h2>



<p>Use fast slow pointers to find the middle point and reverse the second half.</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 pairSum(ListNode* head) {
    auto reverse = [](ListNode* head, ListNode* prev = nullptr) {
      while (head) {
        swap(head-&gt;next, prev);
        swap(head, prev);
      }
      return prev;
    };
    
    ListNode* fast = head;
    ListNode* slow = head;
    while (fast) {
      fast = fast-&gt;next-&gt;next;
      slow = slow-&gt;next;
    }
    
    slow = reverse(slow);
    int ans = 0;
    while (slow) {
      ans = max(ans, head-&gt;val + slow-&gt;val);
      head = head-&gt;next;
      slow = slow-&gt;next;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/">花花酱 LeetCode 2130. Maximum Twin Sum of a Linked List</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/list/leetcode-2130-maximum-twin-sum-of-a-linked-list/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-663ca3b9d2823354348039/]</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 1898. Maximum Number of Removable Characters</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 12 Aug 2021 02:40:40 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subsequence]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8567</guid>

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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumRemovals(string s, string p, vector&lt;int&gt;&amp; removable) {
    const int n = s.length();
    const int t = p.length();
    const int m = removable.size();    
    int l = 0;
    int r = m + 1;
    vector&lt;int&gt; idx(n, INT_MAX);
    for (int i = 0; i &lt; m; ++i)
      idx[removable[i]] = i;
    while (l &lt; r) {
      int mid = l + (r - l) / 2;
      int j = 0;
      for (int i = 0; i &lt; n &amp;&amp; j &lt; t; ++i)
        if (idx[i] &gt;= mid &amp;&amp; s[i] == p[j]) ++j;      
      if (j != t)
        r = mid;
      else
        l = mid + 1;
    }
    // l is the smallest number s.t. p is no longer a subseq of s.
    return l - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/">花花酱 LeetCode 1898. Maximum Number of Removable Characters</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1898-maximum-number-of-removable-characters/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1871. Jump Game VII</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1871-jump-game-vii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1871-jump-game-vii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 06 Aug 2021 05:26:45 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sweep line]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8487</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;binary string&#160;s&#160;and two integers&#160;minJump&#160;and&#160;maxJump. In the beginning, you are standing at index&#160;0, which is equal to&#160;'0'. You can move from index&#160;i&#160;to index&#160;j&#160;if&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1871-jump-game-vii/">花花酱 LeetCode 1871. Jump Game VII</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;binary string&nbsp;<code>s</code>&nbsp;and two integers&nbsp;<code>minJump</code>&nbsp;and&nbsp;<code>maxJump</code>. In the beginning, you are standing at index&nbsp;<code>0</code>, which is equal to&nbsp;<code>'0'</code>. You can move from index&nbsp;<code>i</code>&nbsp;to index&nbsp;<code>j</code>&nbsp;if the following conditions are fulfilled:</p>



<ul><li><code>i + minJump &lt;= j &lt;= min(i + maxJump, s.length - 1)</code>, and</li><li><code>s[j] == '0'</code>.</li></ul>



<p>Return&nbsp;<code>true</code><em>&nbsp;if you can reach index&nbsp;</em><code>s.length - 1</code><em>&nbsp;in&nbsp;</em><code>s</code><em>, or&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "011010", minJump = 2, maxJump = 3
<strong>Output:</strong> true
<strong>Explanation:</strong>
In the first step, move from index 0 to index 3. 
In the second step, move from index 3 to index 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "01101110", minJump = 2, maxJump = 3
<strong>Output:</strong> false
</pre>



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



<ul><li><code>2 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s[i]</code>&nbsp;is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code>.</li><li><code>s[0] == '0'</code></li><li><code>1 &lt;= minJump &lt;= maxJump &lt; s.length</code></li></ul>



<h2><strong>Solution 1: TreeSet /Dequq + Binary Search</strong></h2>



<p>Maintain a set of reachable indices so far, for each &#8216;0&#8217; index check whether it can be reached from any of the elements in the set.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, 296 ms, 59.7MB
class Solution {
public:
  bool canReach(string s, int minJump, int maxJump) {
    if (s.back() != '0') return false;
    const int n = s.length();    
    set&lt;int&gt; seen{0};
    for (int i = minJump; i &lt; n; ++i) {
      if (s[i] != '0') continue;
      while (!seen.empty() &amp;&amp; (*seen.begin()) + maxJump &lt; i)
        seen.erase(seen.begin());
      auto it = seen.upper_bound(i - minJump);
      if (it != seen.begin() &amp;&amp; *prev(it) + minJump &lt;= i)        
        seen.insert(i);
    }
    return seen.count(n - 1);
  }
};</pre>

</div><h2 class="tabtitle">C++/deque</h2>
<div class="tabcontent">

<pre class="crayon-plain-tag">// Author: Huahua, 280 ms, 19MB
class Solution {
public:
  bool canReach(string s, int minJump, int maxJump) {
    if (s.back() != '0') return false;
    const int n = s.length();    
    deque&lt;int&gt; seen{0};
    for (int i = minJump; i &lt; n; ++i) {
      if (s[i] != '0') continue;
      while (!seen.empty() &amp;&amp; (seen.front()) + maxJump &lt; i)
        seen.pop_front();
      auto it = upper_bound(begin(seen), end(seen), i - minJump);
      if (it != seen.begin() &amp;&amp; *prev(it) + minJump &lt;= i)
        seen.push_back(i);
    }
    return seen.back() == n - 1;
  }
};</pre>
</div></div>



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



<p>Same idea, we can replace the deque in sol1 with a queue, and only check the smallest element in the queue.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 56ms, 19.2MB
class Solution {
public:
  bool canReach(string s, int minJump, int maxJump) {
    if (s.back() != '0') return false;
    const int n = s.length();    
    queue&lt;int&gt; q{{0}};
    for (int i = minJump; i &lt; n; ++i) {
      if (s[i] != '0') continue;
      while (!q.empty() &amp;&amp; q.front() + maxJump &lt; i)
        q.pop();
      if (!q.empty() &amp;&amp; q.front() + minJump &lt;= i)
        q.push(i);
    }
    return q.back() == n - 1;
  }
};</pre>
</div></div>



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



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1871-jump-game-vii/">花花酱 LeetCode 1871. Jump Game VII</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1871-jump-game-vii/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 1712. Ways to Split Array Into Three Subarrays</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1712-ways-to-split-array-into-three-subarrays/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1712-ways-to-split-array-into-three-subarrays/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Jan 2021 08:44:40 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[split array]]></category>
		<category><![CDATA[two pointers]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7897</guid>

					<description><![CDATA[<p>A split of an integer array is&#160;good&#160;if: The array is split into three&#160;non-empty&#160;contiguous subarrays &#8211; named&#160;left,&#160;mid,&#160;right&#160;respectively from left to right. The sum of the elements&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1712-ways-to-split-array-into-three-subarrays/">花花酱 LeetCode 1712. Ways to Split Array Into Three Subarrays</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>A split of an integer array is&nbsp;<strong>good</strong>&nbsp;if:</p>



<ul><li>The array is split into three&nbsp;<strong>non-empty</strong>&nbsp;contiguous subarrays &#8211; named&nbsp;<code>left</code>,&nbsp;<code>mid</code>,&nbsp;<code>right</code>&nbsp;respectively from left to right.</li><li>The sum of the elements in&nbsp;<code>left</code>&nbsp;is less than or equal to the sum of the elements in&nbsp;<code>mid</code>, and the sum of the elements in&nbsp;<code>mid</code>&nbsp;is less than or equal to the sum of the elements in&nbsp;<code>right</code>.</li></ul>



<p>Given&nbsp;<code>nums</code>, an array of&nbsp;<strong>non-negative</strong>&nbsp;integers, return&nbsp;<em>the number of&nbsp;<strong>good</strong>&nbsp;ways to split</em>&nbsp;<code>nums</code>. As the number may be too large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9&nbsp;</sup>+ 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only good way to split nums is [1] [1] [1].</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,2,2,5,0]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are three good ways of splitting nums:
[1] [2] [2,2,5,0]
[1] [2,2] [2,5,0]
[1,2] [2,2] [5,0]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,2,1]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is no good way to split nums.</pre>



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



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



<h2><strong>Solution 1: Prefix Sum + Binary Search</strong></h2>



<p>We split the array into [0 &#8230; i] [i + 1&#8230; j] [j + 1 &#8230; n &#8211; 1]<br>we can use binary search to find the min and max of j for each i.<br>s.t.  sum(0 ~ i) &lt;= sums(i + 1 ~j) &lt;= sums(j + 1 ~ n &#8211; 1)<br>min is lower_bound(2 * sums(0 ~ i))<br>max is upper_bound(sums(0 ~ i) + (total &#8211; sums(0 ~ i)) / 2)</p>



<p>Time complexity: O(nlogn)<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 waysToSplit(vector&lt;int&gt;&amp; nums) {
    constexpr int kMod = 1e9 + 7;
    const int n = nums.size();    
    for (int i = 1; i &lt; n; ++i) 
      nums[i] += nums[i - 1];
    const int total = nums.back();
    long ans = 0;  
    // [0 .. i] [i + 1 ... j] [j + 1 ... n - 1]
    for (int i = 0, left = 0; i &lt; n; ++i) {      
      auto it1 = lower_bound(begin(nums) + i + 1, end(nums), 2 * nums[i]);
      auto it2 = upper_bound(begin(nums), end(nums) - 1, nums[i] + (total - nums[i]) / 2);
      if (it2 &lt;= it1) continue;
      ans += it2 - it1;
    }    
    return ans % kMod;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Prefix Sum + Two Pointers</strong></h2>



<p>The right end of the middle array is in range [j, k &#8211; 1] and there are k &#8211; j choices.<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 waysToSplit(vector&lt;int&gt;&amp; nums) {
    constexpr int kMod = 1e9 + 7;
    const int n = nums.size();    
    for (int i = 1; i &lt; n; ++i) 
      nums[i] += nums[i - 1];
    const int total = nums.back();
    long ans = 0;    
    for (int i = 0, j = 0, k = 0; i &lt; n; ++i) {      
      j = max(j, i + 1);
      while (j &lt; n - 1 &amp;&amp; nums[j] &lt; 2 * nums[i]) ++j;
      k = max(k, j);
      while (k &lt; n - 1 &amp;&amp; 2 * nums[k] &lt;= nums[i] + total) ++k;
      ans += (k - j);
    }    
    return ans % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1712-ways-to-split-array-into-three-subarrays/">花花酱 LeetCode 1712. Ways to Split Array Into Three Subarrays</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1712-ways-to-split-array-into-three-subarrays/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
