<?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>sliding window &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/sliding-window/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Sat, 12 Apr 2025 17:10:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.2</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>sliding window &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2024. Maximize the Confusion of an Exam</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2024-maximize-the-confusion-of-an-exam/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2024-maximize-the-confusion-of-an-exam/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 12 Apr 2025 17:09:15 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10343</guid>

					<description><![CDATA[数据规模高达5 *104,我们只能使用O(n)的算法了。 可以想到的就是滑动窗口(sliding window)，由于最长长度未知，我们可以使用动态滑动窗口。 记录当前滑动窗口中T和F出现的次数，如果其中较少的一个&#60;=k，那么就可以全部替换它，使得整个滑动窗口都变成相同的值。如果这个时候滑动窗口长度大于当前最大长度，我们就把滑动窗口变大，右侧+1，并更新最大长度。否则，减少滑动窗口，左侧-1。 时间复杂度：O(n)空间复杂度：O(2) [crayon-68014580ea0cc152659655/]]]></description>
										<content:encoded><![CDATA[
<p>数据规模高达5 *10<sup>4</sup>,我们只能使用O(n)的算法了。</p>



<p>可以想到的就是滑动窗口(sliding window)，由于最长长度未知，我们可以使用动态滑动窗口。</p>



<p>记录当前滑动窗口中T和F出现的次数，如果其中较少的一个&lt;=k，那么就可以全部替换它，使得整个滑动窗口都变成相同的值。如果这个时候滑动窗口长度大于当前最大长度，我们就把滑动窗口变大，右侧+1，并更新最大长度。否则，减少滑动窗口，左侧-1。</p>



<p>时间复杂度：O(n)<br>空间复杂度：O(2)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int maxConsecutiveAnswers(string_view A, int k) {
    int ans = 0;
    int f = 0;
    array&lt;int, 2&gt; count; // number of 'F' and 'T' in the sliding window
    for (int i = 0; i &lt; A.size(); ++i) {
      ++count[A[i] == 'T'];
      if (min(count[0], count[1]) &lt;= k &amp;&amp; count[0] + count[1] &gt; ans)
        ++ans;
      else
        --count[A[i - ans] == 'T'];
    }
    return ans;
  }
};</pre>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2024-maximize-the-confusion-of-an-exam/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2653. Sliding Subarray Beauty</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2653-sliding-subarray-beauty/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2653-sliding-subarray-beauty/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 28 Apr 2023 04:43:28 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[counter]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9996</guid>

					<description><![CDATA[Given an integer array&#160;nums&#160;containing&#160;n&#160;integers, find the&#160;beauty&#160;of each subarray of size&#160;k. The&#160;beauty&#160;of a subarray is the&#160;xth&#160;smallest integer&#160;in the subarray if it is&#160;negative, or&#160;0&#160;if there are fewer&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>&nbsp;containing&nbsp;<code>n</code>&nbsp;integers, find the&nbsp;<strong>beauty</strong>&nbsp;of each subarray of size&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>beauty</strong>&nbsp;of a subarray is the&nbsp;<code>x<sup>th</sup></code><strong>&nbsp;smallest integer&nbsp;</strong>in the subarray if it is&nbsp;<strong>negative</strong>, or&nbsp;<code>0</code>&nbsp;if there are fewer than&nbsp;<code>x</code>&nbsp;negative integers.</p>



<p>Return&nbsp;<em>an integer array containing&nbsp;</em><code>n - k + 1</code>&nbsp;<em>integers, which denote the&nbsp;</em><strong>beauty</strong><em>&nbsp;of the subarrays&nbsp;<strong>in order</strong>&nbsp;from the first index in the array.</em></p>



<ul class="wp-block-list"><li>A subarray is a contiguous&nbsp;<strong>non-empty</strong>&nbsp;sequence of elements within an array.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-1,-3,-2,3], k = 3, x = 2
<strong>Output:</strong> [-1,-2,-2]
<strong>Explanation:</strong> There are 3 subarrays with size k = 3. 
The first subarray is <code>[1, -1, -3]</code> and the 2<sup>nd</sup> smallest negative integer is -1.&nbsp;
The second subarray is <code>[-1, -3, -2]</code> and the 2<sup>nd</sup> smallest negative integer is -2.&nbsp;
The third subarray is <code>[-3, -2, 3]&nbsp;</code>and the 2<sup>nd</sup> smallest negative integer is -2.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-1,-2,-3,-4,-5], k = 2, x = 2
<strong>Output:</strong> [-1,-2,-3,-4]
<strong>Explanation:</strong> There are 4 subarrays with size k = 2.
For <code>[-1, -2]</code>, the 2<sup>nd</sup> smallest negative integer is -1.
For <code>[-2, -3]</code>, the 2<sup>nd</sup> smallest negative integer is -2.
For <code>[-3, -4]</code>, the 2<sup>nd</sup> smallest negative integer is -3.
For <code>[-4, -5]</code>, the 2<sup>nd</sup> smallest negative integer is -4.&nbsp;</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-3,1,2,-3,0,-3], k = 2, x = 1
<strong>Output:</strong> [-3,0,-3,-3,-3]
<strong>Explanation:</strong> There are 5 subarrays with size k = 2<strong>.</strong>
For <code>[-3, 1]</code>, the 1<sup>st</sup> smallest negative integer is -3.
For <code>[1, 2]</code>, there is no negative integer so the beauty is 0.
For <code>[2, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.
For <code>[-3, 0]</code>, the 1<sup>st</sup> smallest negative integer is -3.
For <code>[0, -3]</code>, the 1<sup>st</sup> smallest negative integer is -3.</pre>



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



<ul class="wp-block-list"><li><code>n == nums.length&nbsp;</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= k &lt;= n</code></li><li><code>1 &lt;= x &lt;= k&nbsp;</code></li><li><code>-50&nbsp;&lt;= nums[i] &lt;= 50&nbsp;</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window + Counter</strong></h2>



<p>Since the range of nums are very small (-50 ~ 50), we can use a counter to track the frequency of each element, s.t. we can find the k-the smallest element in O(50) instead of O(k).</p>



<p>Time complexity: O((n &#8211; k + 1) * 50)<br>Space complexity: O(50)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; getSubarrayBeauty(vector&lt;int&gt;&amp; nums, int k, int x) {
    constexpr int kMax = 50;    
    const int n = nums.size();
    vector&lt;int&gt; counts(2 * kMax + 1);
    vector&lt;int&gt; ans;    
    for (int i = 0; i &lt; n; ++i) {
      if (i &gt;= k)
        --counts[nums[i - k] + kMax];
      ++counts[nums[i] + kMax];      
      if (i &gt;= k - 1) {
        int b = 0;
        for (int j = 0, s = 0; j &lt;= kMax; ++j) {
          s += counts[j];
          if (s &gt;= x) {
            b = j - kMax;
            break;
          }
        }
        ans.push_back(b);
      }
     
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2653-sliding-subarray-beauty/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2156. Find Substring With Given Hash Value</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2156-find-substring-with-given-hash-value/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2156-find-substring-with-given-hash-value/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 06 Feb 2022 02:19:25 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[rolling hash]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9487</guid>

					<description><![CDATA[The hash of a&#160;0-indexed&#160;string&#160;s&#160;of length&#160;k, given integers&#160;p&#160;and&#160;m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0&#160;+ val(s[1]) * p1&#160;+ ... +&#8230;]]></description>
										<content:encoded><![CDATA[
<p>The hash of a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>s</code>&nbsp;of length&nbsp;<code>k</code>, given integers&nbsp;<code>p</code>&nbsp;and&nbsp;<code>m</code>, is computed using the following function:</p>



<ul class="wp-block-list"><li><code>hash(s, p, m) = (val(s[0]) * p<sup>0</sup>&nbsp;+ val(s[1]) * p<sup>1</sup>&nbsp;+ ... + val(s[k-1]) * p<sup>k-1</sup>) mod m</code>.</li></ul>



<p>Where&nbsp;<code>val(s[i])</code>&nbsp;represents the index of&nbsp;<code>s[i]</code>&nbsp;in the alphabet from&nbsp;<code>val('a') = 1</code>&nbsp;to&nbsp;<code>val('z') = 26</code>.</p>



<p>You are given a string&nbsp;<code>s</code>&nbsp;and the integers&nbsp;<code>power</code>,&nbsp;<code>modulo</code>,&nbsp;<code>k</code>, and&nbsp;<code>hashValue.</code>&nbsp;Return&nbsp;<code>sub</code>,<em>&nbsp;the&nbsp;<strong>first</strong>&nbsp;<strong>substring</strong>&nbsp;of&nbsp;</em><code>s</code><em>&nbsp;of length&nbsp;</em><code>k</code><em>&nbsp;such that&nbsp;</em><code>hash(sub, power, modulo) == hashValue</code>.</p>



<p>The test cases will be generated such that an answer always&nbsp;<strong>exists</strong>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
<strong>Output:</strong> "ee"
<strong>Explanation:</strong> The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. 
"ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
<strong>Output:</strong> "fbx"
<strong>Explanation:</strong> The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 31<sup>2</sup>) mod 100 = 23132 mod 100 = 32. 
The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 31<sup>2</sup>) mod 100 = 25732 mod 100 = 32. 
"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
Note that "bxz" also has a hash of 32 but it appears later than "fbx".
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= s.length &lt;= 2 * 10<sup>4</sup></code></li><li><code>1 &lt;= power, modulo &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= hashValue &lt; modulo</code></li><li><code>s</code>&nbsp;consists of lowercase English letters only.</li><li>The test cases are generated such that an answer always&nbsp;<strong>exists</strong>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding window</strong></h2>



<p>hash = (((<meta charset="utf-8">hash &#8211; (s[i+k] * p<sup>k-1</sup>) % mod + mod) * p) + (s[i] * p<sup>0</sup>)) % mod</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string subStrHash(string s, int power, int modulo, int k, int hashValue) {    
    const int n = s.length();
    long p = 1; 
    for (int i = 1; i &lt; k; ++i)
      p = (p * power) % modulo;
    long ans = 0;
    for (long i = n - 1, cur = 0; i &gt;= 0; --i) {
      if (i + k &lt; n) 
        cur = ((cur - (s[i + k] - 'a' + 1) * p) % modulo + modulo) % modulo;
      cur = (cur * power + (s[i] - 'a' + 1)) % modulo;      
      if (i + k &lt;= n &amp;&amp; cur == hashValue) 
        ans = i;
    }    
    return s.substr(ans, k);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2156-find-substring-with-given-hash-value/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2134. Minimum Swaps to Group All 1&#8217;s Together II</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2134-minimum-swaps-to-group-all-1s-together-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2134-minimum-swaps-to-group-all-1s-together-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 18 Jan 2022 01:13:22 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9424</guid>

					<description><![CDATA[A&#160;swap&#160;is defined as taking two&#160;distinct&#160;positions in an array and swapping the values in them. A&#160;circular&#160;array is defined as an array where we consider the&#160;first&#160;element and&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>swap</strong>&nbsp;is defined as taking two&nbsp;<strong>distinct</strong>&nbsp;positions in an array and swapping the values in them.</p>



<p>A&nbsp;<strong>circular</strong>&nbsp;array is defined as an array where we consider the&nbsp;<strong>first</strong>&nbsp;element and the&nbsp;<strong>last</strong>&nbsp;element to be&nbsp;<strong>adjacent</strong>.</p>



<p>Given a&nbsp;<strong>binary</strong>&nbsp;<strong>circular</strong>&nbsp;array&nbsp;<code>nums</code>, return&nbsp;<em>the minimum number of swaps required to group all&nbsp;</em><code>1</code><em>&#8216;s present in the array together at&nbsp;<strong>any location</strong></em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,0,1,1,0,0]
<strong>Output:</strong> 1
<strong>Explanation:</strong> Here are a few of the ways to group all the 1's together:
[0,0,1,1,1,0,0] using 1 swap.
[0,1,1,1,0,0,0] using 1 swap.
[1,1,0,0,0,0,1] using 2 swaps (using the circular property of the array).
There is no way to group all 1's together with 0 swaps.
Thus, the minimum number of swaps required is 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,1,1,1,0,0,1,1,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong> Here are a few of the ways to group all the 1's together:
[1,1,1,0,0,0,0,1,1] using 2 swaps (using the circular property of the array).
[1,1,1,1,1,0,0,0,0] using 2 swaps.
There is no way to group all 1's together with 0 or 1 swaps.
Thus, the minimum number of swaps required is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,0,0,1]
<strong>Output:</strong> 0
<strong>Explanation:</strong> All the 1's are already grouped together due to the circular property of the array.
Thus, the minimum number of swaps required is 0.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>nums[i]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<p>Step 1: Count how many ones are there in the array. Assume it&#8217;s K.<br>Step 2: For each window of size k, count how many ones in the window, we have to swap 0s out with 1s to fill the window. ans = min(ans, k &#8211; ones).</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minSwaps(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    const int k = accumulate(begin(nums), end(nums), 0);
    int ans = INT_MAX;
    for (int i = 0, cur = 0; i &lt; n + k; ++i) {
      if (i &gt;= k) cur -= nums[(i - k + n) % n];
      cur += nums[i % n];      
      ans = min(ans, k - cur);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2134-minimum-swaps-to-group-all-1s-together-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1984. Minimum Difference Between Highest and Lowest of K Scores</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 31 Dec 2021 23:59:40 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9363</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums, where&#160;nums[i]&#160;represents the score of the&#160;ith&#160;student. You are also given an integer&#160;k. Pick the scores of any&#160;k&#160;students from the array so&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, where&nbsp;<code>nums[i]</code>&nbsp;represents the score of the&nbsp;<code>i<sup>th</sup></code>&nbsp;student. You are also given an integer&nbsp;<code>k</code>.</p>



<p>Pick the scores of any&nbsp;<code>k</code>&nbsp;students from the array so that the&nbsp;<strong>difference</strong>&nbsp;between the&nbsp;<strong>highest</strong>&nbsp;and the&nbsp;<strong>lowest</strong>&nbsp;of the&nbsp;<code>k</code>&nbsp;scores is&nbsp;<strong>minimized</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;possible difference</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [90], k = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> There is one way to pick score(s) of one student:
- [<strong><u>90</u></strong>]. The difference between the highest and lowest score is 90 - 90 = 0.
The minimum possible difference is 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [9,4,1,7], k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are six ways to pick score(s) of two students:
- [<strong><u>9</u></strong>,<strong><u>4</u></strong>,1,7]. The difference between the highest and lowest score is 9 - 4 = 5.
- [<strong><u>9</u></strong>,4,<strong><u>1</u></strong>,7]. The difference between the highest and lowest score is 9 - 1 = 8.
- [<strong><u>9</u></strong>,4,1,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 9 - 7 = 2.
- [9,<strong><u>4</u></strong>,<strong><u>1</u></strong>,7]. The difference between the highest and lowest score is 4 - 1 = 3.
- [9,<strong><u>4</u></strong>,1,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 7 - 4 = 3.
- [9,4,<strong><u>1</u></strong>,<strong><u>7</u></strong>]. The difference between the highest and lowest score is 7 - 1 = 6.
The minimum possible difference is 2.</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= k &lt;= nums.length &lt;= 1000</code></li><li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<p>Sort the array, to minimize the difference, k numbers must be consecutive (i.e, from a subarray). We use a sliding window size of k and try all possible subarrays. <br>Ans = min{(nums[k &#8211; 1] &#8211; nums[0]), (nums[k] &#8211; nums[1]), &#8230; (nums[n &#8211; 1] &#8211; nums[n &#8211; k])}</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumDifference(vector&lt;int&gt;&amp; nums, int k) {
    int ans = INT_MAX;
    sort(begin(nums), end(nums));
    for (int i = k - 1; i &lt; nums.size(); ++i)
      ans = min(ans, nums[i] - nums[i - k + 1]);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1984-minimum-difference-between-highest-and-lowest-of-k-scores/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 13 Dec 2021 02:49:45 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[range query]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9171</guid>

					<description><![CDATA[Problem Solution 1: Range sum query Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"><strong><a href="http://2106. Maximum Fruits Harvested After at Most K Steps">Problem</a></strong></h2>



<p></p>



<h2 class="wp-block-heading"><strong>Solution 1: Range sum query</strong></h2>



<p>Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of those fruits.</p>



<p>Given startPos and k, we have four options:<br>1. move i steps to the left<br>2. move i steps to the left and k &#8211; i steps to the right.<br>3. move i steps to the right<br>4. move i steps to the right and k &#8211; i steps to the left.</p>



<p>We enumerate i steps and calculate maximum range [l, r] covered by each option, and collect all the fruit in that range.</p>



<p>Time complexity: O(m + k)<br>Space complexity: O(m)<br>where m = max(max(pos), startPos)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    const int m = max(startPos, (*max_element(begin(fruits), end(fruits)))[0]);
    vector&lt;int&gt; sums(m + 2);   
    for (int i = 0, j = 0; i &lt;= m; ++i) {
      sums[i + 1] += sums[i];
      while (j &lt; fruits.size() &amp;&amp; fruits[j][0] == i)        
        sums[i + 1] += fruits[j++][1];      
    }    
    int ans = 0;
    for (int s = 0; s &lt;= k; ++s) {
      if (startPos - s &gt;= 0) {
        int l = startPos - s;
        int r = min(max(startPos, l + (k - s)), m);        
        ans = max(ans, sums[r + 1] - sums[l]);
      }
      if (startPos + s &lt;= m) {
        int r = startPos + s;
        int l = max(0, min(startPos, r - (k - s)));
        ans = max(ans, sums[r + 1] - sums[l]);
      }
    }             
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Sliding Window</strong></h2>



<p>Maintain a window [l, r] such that the steps to cover [l, r] from startPos is less or equal to k.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    auto steps = [&amp;](int l, int r) {
      if (r &lt;= startPos)
        return startPos - l;
      else if (l &gt;= startPos)
        return r - startPos;
      else
        return min(startPos + r - 2 * l, 2 * r - startPos - l);
    };
    int ans = 0;
    for (int r = 0, l = 0, cur = 0; r &lt; fruits.size(); ++r) {
      cur += fruits[r][1];
      while (l &lt;= r &amp;&amp; steps(fruits[l][0], fruits[r][0]) &gt; k)
        cur -= fruits[l++][1];      
      ans = max(ans, cur);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 219. Contains Duplicate II</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-219-contains-duplicate-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-219-contains-duplicate-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 06 Dec 2021 04:13:40 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9056</guid>

					<description><![CDATA[Given an integer array&#160;nums&#160;and an integer&#160;k, return&#160;true&#160;if there are two&#160;distinct indices&#160;i&#160;and&#160;j&#160;in the array such that&#160;nums[i] == nums[j]&#160;and&#160;abs(i - j) &#60;= k. Example 1: Input: nums&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>, return&nbsp;<code>true</code>&nbsp;if there are two&nbsp;<strong>distinct indices</strong>&nbsp;<code>i</code>&nbsp;and&nbsp;<code>j</code>&nbsp;in the array such that&nbsp;<code>nums[i] == nums[j]</code>&nbsp;and&nbsp;<code>abs(i - j) &lt;= k</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,1], k = 3
<strong>Output:</strong> true
</pre>



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



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



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li></ul>



<p><strong>Solution: Sliding Window + Hashtable</strong></p>



<p>Hashtable to store the last index of a number.</p>



<p>Remove the number if it&#8217;s k steps behind the current position.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  bool containsNearbyDuplicate(vector&lt;int&gt;&amp; nums, int k) {
    unordered_map&lt;int, int&gt; m; // num -&gt; last index
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (i &gt; k &amp;&amp; m[nums[i - k - 1]] &lt; i - k + 1)
        m.erase(nums[i - k - 1]);
      if (m.count(nums[i])) return true;
      m[nums[i]] = i;
    }
    return false;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-219-contains-duplicate-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2090. K Radius Subarray Averages</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2090-k-radius-subarray-averages/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2090-k-radius-subarray-averages/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 28 Nov 2021 16:53:38 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[moving average]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8853</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;array&#160;nums&#160;of&#160;n&#160;integers, and an integer&#160;k. The&#160;k-radius average&#160;for a subarray of&#160;nums&#160;centered&#160;at some index&#160;i&#160;with the&#160;radius&#160;k&#160;is the average of&#160;all&#160;elements in&#160;nums&#160;between the indices&#160;i - k&#160;and&#160;i + k&#160;(inclusive).&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array&nbsp;<code>nums</code>&nbsp;of&nbsp;<code>n</code>&nbsp;integers, and an integer&nbsp;<code>k</code>.</p>



<p>The&nbsp;<strong>k-radius average</strong>&nbsp;for a subarray of&nbsp;<code>nums</code>&nbsp;<strong>centered</strong>&nbsp;at some index&nbsp;<code>i</code>&nbsp;with the&nbsp;<strong>radius</strong>&nbsp;<code>k</code>&nbsp;is the average of&nbsp;<strong>all</strong>&nbsp;elements in&nbsp;<code>nums</code>&nbsp;between the indices&nbsp;<code>i - k</code>&nbsp;and&nbsp;<code>i + k</code>&nbsp;(<strong>inclusive</strong>). If there are less than&nbsp;<code>k</code>&nbsp;elements before&nbsp;<strong>or</strong>&nbsp;after the index&nbsp;<code>i</code>, then the&nbsp;<strong>k-radius average</strong>&nbsp;is&nbsp;<code>-1</code>.</p>



<p>Build and return&nbsp;<em>an array&nbsp;</em><code>avgs</code><em>&nbsp;of length&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>avgs[i]</code><em>&nbsp;is the&nbsp;<strong>k-radius average</strong>&nbsp;for the subarray centered at index&nbsp;</em><code>i</code>.</p>



<p>The&nbsp;<strong>average</strong>&nbsp;of&nbsp;<code>x</code>&nbsp;elements is the sum of the&nbsp;<code>x</code>&nbsp;elements divided by&nbsp;<code>x</code>, using&nbsp;<strong>integer division</strong>. The integer division truncates toward zero, which means losing its fractional part.</p>



<ul class="wp-block-list"><li>For example, the average of four elements&nbsp;<code>2</code>,&nbsp;<code>3</code>,&nbsp;<code>1</code>, and&nbsp;<code>5</code>&nbsp;is&nbsp;<code>(2 + 3 + 1 + 5) / 4 = 11 / 4 = 2.75</code>, which truncates to&nbsp;<code>2</code>.</li></ul>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2021/11/07/eg1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [7,4,3,9,1,8,5,2,6], k = 3
<strong>Output:</strong> [-1,-1,-1,5,4,4,-1,-1,-1]
<strong>Explanation:</strong>
- avg[0], avg[1], and avg[2] are -1 because there are less than k elements <strong>before</strong> each index.
- The sum of the subarray centered at index 3 with radius 3 is: 7 + 4 + 3 + 9 + 1 + 8 + 5 = 37.
  Using <strong>integer division</strong>, avg[3] = 37 / 7 = 5.
- For the subarray centered at index 4, avg[4] = (4 + 3 + 9 + 1 + 8 + 5 + 2) / 7 = 4.
- For the subarray centered at index 5, avg[5] = (3 + 9 + 1 + 8 + 5 + 2 + 6) / 7 = 4.
- avg[6], avg[7], and avg[8] are -1 because there are less than k elements <strong>after</strong> each index.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [100000], k = 0
<strong>Output:</strong> [100000]
<strong>Explanation:</strong>
- The sum of the subarray centered at index 0 with radius 0 is: 100000.
  avg[0] = 100000 / 1 = 100000.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [8], k = 100000
<strong>Output:</strong> [-1]
<strong>Explanation:</strong> 
- avg[0] is -1 because there are less than k elements before and after index 0.
</pre>



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



<ul class="wp-block-list"><li><code>n == nums.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= nums[i], k &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<p>We compute i &#8211; k&#8217;s average at position 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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; getAverages(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    long long sum = 0;
    vector&lt;int&gt; ans(n, -1);    
    for (int i = 0; i &lt; n; ++i) {
      sum += nums[i];
      if (i &gt;= 2 * k) {
        ans[i - k] = sum / (2 * k + 1);           
        sum -= nums[i - 2 * k];
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2090-k-radius-subarray-averages/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2009. Minimum Number of Operations to Make Array Continuous</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 26 Nov 2021 20:32:13 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[unique]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8780</guid>

					<description><![CDATA[You are given an integer array&#160;nums. In one operation, you can replace&#160;any&#160;element in&#160;nums&#160;with&#160;any&#160;integer. nums&#160;is considered&#160;continuous&#160;if both of the following conditions are fulfilled: All elements in&#160;nums&#160;are&#160;unique.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>. In one operation, you can replace&nbsp;<strong>any</strong>&nbsp;element in&nbsp;<code>nums</code>&nbsp;with&nbsp;<strong>any</strong>&nbsp;integer.</p>



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



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



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



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



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



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



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



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



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



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



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; A) {
    const int n = A.size();
    sort(begin(A), end(A));
    A.erase(unique(begin(A), end(A)), end(A));    
    int ans = INT_MAX;
    for (int i = 0, j = 0, m = A.size(); i &lt; m; ++i) {
      while (j &lt; m &amp;&amp; A[j] &lt; A[i] + n) ++j;
      ans = min(ans, n - (j - i));
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2009-minimum-number-of-operations-to-make-array-continuous/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2062. Count Vowel Substrings of a String</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2062-count-vowel-substrings-of-a-string/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2062-count-vowel-substrings-of-a-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 07 Nov 2021 07:00:45 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8669</guid>

					<description><![CDATA[A&#160;substring&#160;is a contiguous (non-empty) sequence of characters within a string. A&#160;vowel substring&#160;is a substring that&#160;only&#160;consists of vowels ('a',&#160;'e',&#160;'i',&#160;'o', and&#160;'u') and has&#160;all five&#160;vowels present in it.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A&nbsp;<strong>substring</strong>&nbsp;is a contiguous (non-empty) sequence of characters within a string.</p>



<p>A&nbsp;<strong>vowel substring</strong>&nbsp;is a substring that&nbsp;<strong>only</strong>&nbsp;consists of vowels (<code>'a'</code>,&nbsp;<code>'e'</code>,&nbsp;<code>'i'</code>,&nbsp;<code>'o'</code>, and&nbsp;<code>'u'</code>) and has&nbsp;<strong>all five</strong>&nbsp;vowels present in it.</p>



<p>Given a string&nbsp;<code>word</code>, return&nbsp;<em>the number of&nbsp;<strong>vowel substrings</strong>&nbsp;in</em>&nbsp;<code>word</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "aeiouu"
<strong>Output:</strong> 2
<strong>Explanation:</strong> The vowel substrings of word are as follows (underlined):
- "<strong><u>aeiou</u></strong>u"
- "<strong><u>aeiouu</u></strong>"
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "unicornarihan"
<strong>Output:</strong> 0
<strong>Explanation:</strong> Not all 5 vowels are present, so there are no vowel substrings.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "cuaieuouac"
<strong>Output:</strong> 7
<strong>Explanation:</strong> The vowel substrings of word are as follows (underlined):
- "c<strong><u>uaieuo</u></strong>uac"
- "c<strong><u>uaieuou</u></strong>ac"
- "c<strong><u>uaieuoua</u></strong>c"
- "cu<strong><u>aieuo</u></strong>uac"
- "cu<strong><u>aieuou</u></strong>ac"
- "cu<strong><u>aieuoua</u></strong>c"
- "cua<strong><u>ieuoua</u></strong>c"</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> word = "bbaeixoubb"
<strong>Output:</strong> 0
<strong>Explanation:</strong> The only substrings that contain all five vowels also contain consonants, so there are no vowel substrings.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= word.length &lt;= 100</code></li><li><code>word</code>&nbsp;consists of lowercase English letters only.</li></ul>



<p>Solution 1: Brute Force</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countVowelSubstrings(string_view word) {
    const int n = word.size();
    auto check = [&amp;](string_view s) {
      set&lt;int&gt; seen;
      string vowels {&quot;aeiou&quot;};
      for (char c : s) {
        if (vowels.find(c) == string::npos) return false;
        seen.insert(c);
      }
      return seen.size() == 5;
    };
    int ans = 0;
    for (int i = 0; i &lt; n; ++i)
      for (int l = 5; i + l &lt;= n; ++l)
        if (check(word.substr(i, l))) ++ans;
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Sliding Window</strong> <strong>/ Three Pointers</strong></h2>



<p>Maintain a window [i, j] that contain all 5 vowels, find k s.t. [k + 1, i] no longer container 5 vowels.<br># of valid substrings end with j will be (k &#8211; i).</p>



<p><code>##<span class="has-inline-color has-vivid-cyan-blue-color">aeiou</span><span class="has-inline-color has-vivid-red-color">aeioo</span>##</code><br><code>..i....k...j..</code><br>i = 3, k = 8, j = 12</p>



<p>Valid substrings are:<br><code>aeiouaeioo<br>.eiouaeioo<br>..iouaeioo<br>...ouaeioo<br>....uaeioo</code><br>8 &#8211; 3 = 5</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int countVowelSubstrings(string_view word) {    
    constexpr string_view vowels{&quot;aeiou&quot;};
    int ans = 0;
    unordered_map&lt;char, int&gt; m;
    for (char c : vowels) m[c] = 0;
    for (size_t i = 0, j = 0, k = 0, v = 0; j &lt; word.size(); ++j) {
      if (m.count(word[j])) {
        v += (++m[word[j]] == 1);
        while (v == 5)
          v -= (--m[word[k++]] == 0);
        ans += k - i;
      } else {
        for (char c : vowels) m[c] = 0;
        v = 0;
        i = k = j + 1;
      }
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-2062-count-vowel-substrings-of-a-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1888. Minimum Number of Flips to Make the Binary String Alternating</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1888-minimum-number-of-flips-to-make-the-binary-string-alternating/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1888-minimum-number-of-flips-to-make-the-binary-string-alternating/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Aug 2021 01:49:44 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8543</guid>

					<description><![CDATA[You are given a binary string&#160;s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove&#160;the character at&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a binary string&nbsp;<code>s</code>. You are allowed to perform two types of operations on the string in any sequence:</p>



<ul class="wp-block-list"><li><strong>Type-1: Remove</strong>&nbsp;the character at the start of the string&nbsp;<code>s</code>&nbsp;and&nbsp;<strong>append</strong>&nbsp;it to the end of the string.</li><li><strong>Type-2: Pick</strong>&nbsp;any character in&nbsp;<code>s</code>&nbsp;and&nbsp;<strong>flip</strong>&nbsp;its value, i.e., if its value is&nbsp;<code>'0'</code>&nbsp;it becomes&nbsp;<code>'1'</code>&nbsp;and vice-versa.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of&nbsp;<strong>type-2</strong>&nbsp;operations you need to perform</em>&nbsp;<em>such that&nbsp;</em><code>s</code>&nbsp;<em>becomes&nbsp;<strong>alternating</strong>.</em></p>



<p>The string is called&nbsp;<strong>alternating</strong>&nbsp;if no two adjacent characters are equal.</p>



<ul class="wp-block-list"><li>For example, the strings&nbsp;<code>"010"</code>&nbsp;and&nbsp;<code>"1010"</code>&nbsp;are alternating, while the string&nbsp;<code>"0100"</code>&nbsp;is not.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "111000"
<strong>Output:</strong> 2
<strong>Explanation</strong>: Use the first operation two times to make s = "100011".
Then, use the second operation on the third and sixth elements to make s = "101010".
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "010"
<strong>Output:</strong> 0
<strong>Explanation</strong>: The string is already alternating.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "1110"
<strong>Output:</strong> 1
<strong>Explanation</strong>: Use the second operation on the second element to make s = "1010".
</pre>



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



<ul class="wp-block-list"><li><code>1 &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></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<p>Trying all possible rotations will take O(n<sup>2</sup>) that leads to TLE, we have to do better.</p>



<p>concatenate the s to itself, then using a sliding window length of n to check how many count needed to make the string in the window alternating which will cover all possible rotations. We can update the count in O(1) when moving to the next window.</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 lang="c++">
// Author: Huahua
class Solution {
public:
  int minFlips(string s) {
    const int n = s.length();    
    int ans = INT_MAX;
    for (int i = 0, c0 = 0, c1 = 1, a0 = 0, a1 = 0; i < 2 * n; ++i, c0 ^= 1, c1 ^= 1) {
      if (s[i % n] - '0' != c0) ++a0;
      if (s[i % n] - '0' != c1) ++a1;
      if (i < n - 1) continue;
      if (i >= n) {
        if (s[i - n] - '0' != c0 ^ (n & 1)) --a0;
        if (s[i - n] - '0' != c1 ^ (n & 1)) --a1;
      }
      ans = min({ans, a0, a1});      
    }    
    return ans;
  }
};
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1888-minimum-number-of-flips-to-make-the-binary-string-alternating/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1838. Frequency of the Most Frequent Element</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Apr 2021 16:28:49 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sort]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8388</guid>

					<description><![CDATA[The&#160;frequency&#160;of an element is the number of times it occurs in an array. You are given an integer array&#160;nums&#160;and an integer&#160;k. In one operation, you&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1838. Frequency of the Most Frequent Element - 刷题找工作 EP392" width="500" height="281" src="https://www.youtube.com/embed/KhQOPSa09Fs?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>The&nbsp;<strong>frequency</strong>&nbsp;of an element is the number of times it occurs in an array.</p>



<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. In one operation, you can choose an index of&nbsp;<code>nums</code>&nbsp;and increment the element at that index by&nbsp;<code>1</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum possible frequency</strong>&nbsp;of an element after performing&nbsp;<strong>at most</strong>&nbsp;</em><code>k</code><em>&nbsp;operations</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,4], k = 5
<strong>Output:</strong> 3<strong>
Explanation:</strong> Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,8,13], k = 5
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,9,6], k = 2
<strong>Output:</strong> 1
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png" alt="" class="wp-image-8391" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



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



<figure class="wp-block-image size-large"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png" alt="" class="wp-image-8394" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2021/04/1838-ep392-3-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<p>Sort the elements, maintain a window such that it takes at most k ops to make the all the elements equal to nums[i].</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="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int maxFrequency(vector&lt;int&gt;&amp; nums, int k) {
    sort(begin(nums), end(nums));
    int l = 0;
    long sum = 0;
    int ans = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      sum += nums[r];      
      while (l &lt; r &amp;&amp; 
             sum + k &lt; static_cast&lt;long&gt;(nums[r]) * (r - l + 1))
        sum -= nums[l++];
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1838-frequency-of-the-most-frequent-element/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 07:56:26 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[consecutive]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7853</guid>

					<description><![CDATA[You are given an integer array,&#160;nums, and an integer&#160;k.&#160;nums&#160;comprises of only&#160;0&#8216;s and&#160;1&#8216;s. In one move, you can choose two&#160;adjacent&#160;indices and swap their values. Return&#160;the&#160;minimum&#160;number of&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array,&nbsp;<code>nums</code>, and an integer&nbsp;<code>k</code>.&nbsp;<code>nums</code>&nbsp;comprises of only&nbsp;<code>0</code>&#8216;s and&nbsp;<code>1</code>&#8216;s. In one move, you can choose two&nbsp;<strong>adjacent</strong>&nbsp;indices and swap their values.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of moves required so that&nbsp;</em><code>nums</code><em>&nbsp;has&nbsp;</em><code>k</code><em>&nbsp;<strong>consecutive</strong>&nbsp;</em><code>1</code><em>&#8216;s</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,1,0,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,0,0,0,1,1], k = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,0,1], k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> nums already has 2 consecutive 1's.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>nums[i]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li><li><code>1 &lt;= k &lt;= sum(nums)</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Prefix Sum + Sliding Window</strong></h2>



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



<p>We only care positions of 1s, we can move one element from position x to y (assuming x + 1 ~ y are all zeros) in y &#8211; x steps. e.g. [0 0 1 0 0 0 1] =&gt; [0 0 0 0 0 1 1], move first 1 at position 2 to position 5, cost is 5 &#8211; 2 = 3.</p>



<p>Given a size k window of indices of ones, the optimal solution it to use the median number as center. We can compute the cost to form consecutive numbers:</p>



<p>e.g. [1 4 7 9 10] =&gt; [5 6 7 8 9] cost = (5 &#8211; 1) + (6 &#8211; 4) + (9 &#8211; 8) + (10 &#8211; 9) = 8</p>



<p>However, naive solution takes O(n*k) =&gt; TLE.</p>



<p>We can use prefix sum to compute the cost of a window in O(1) to reduce time complexity to O(n)</p>



<p>First, in order to use sliding window, we change the target of every number in the window to the median number.<br>e.g. [1 4 7 9 10] =&gt; [7 7 7 7 7] cost = (7 &#8211; 1) + (7 &#8211; 4) + (7 &#8211; 7) + (9 &#8211; 7) + (10 &#8211; 7) = (9 + 10) &#8211; (1 + 4) = right &#8211; left. <br>[5 6 7 8 9] =&gt; [7 7 7 7 7] takes extra 2 + 1 + 1 + 2 = 6 steps =  (k / 2) * ((k + 1) / 2), these extra steps should be deducted from the final answer. </p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minMoves(vector&lt;int&gt;&amp; nums, int k) {
    vector&lt;long&gt; s(1);
    for (int i = 0; i &lt; nums.size(); ++i)
      if (nums[i])
        s.push_back(s.back() + i);
    const int n = s.size();
    long ans = 1e10;
    const int m1 = k / 2, m2 = (k + 1) / 2;
    for (int i = 0; i + k &lt; n; ++i) {
      const long right = s[i + k] - s[i + m1];
      const long left = s[i + m2] - s[i];
      ans = min(ans, right - left);
    }
    return ans - m1 * m2;
  }
};</pre>

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

<pre class="urvanov-syntax-highlighter-plain-tag">class Solution:
  def minMoves(self, nums: List[int], k: int) -&gt; int:
    ans = 1e10
    s = [0]    
    for i, v in enumerate(nums):
      if v: s.append(s[-1] + i)
    n = len(s)
    m1 = k // 2
    m2 = (k + 1) // 2
    for i in range(n - k):
      right = s[i + k] - s[i + m1]
      left = s[i + m2] - s[i]
      ans = min(ans, right - left)
    return ans - m1 * m2</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1695. Maximum Erasure Value</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1695-maximum-erasure-value/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1695-maximum-erasure-value/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 20 Dec 2020 09:14:16 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[hashset]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7823</guid>

					<description><![CDATA[You are given an array of positive integers&#160;nums&#160;and want to erase a subarray containing&#160;unique elements. The&#160;score&#160;you get by erasing the subarray is equal to the&#160;sum&#160;of&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of positive integers&nbsp;<code>nums</code>&nbsp;and want to erase a subarray containing&nbsp;<strong>unique elements</strong>. The&nbsp;<strong>score</strong>&nbsp;you get by erasing the subarray is equal to the&nbsp;<strong>sum</strong>&nbsp;of its elements.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum score</strong>&nbsp;you can get by erasing&nbsp;<strong>exactly one</strong>&nbsp;subarray.</em></p>



<p>An array&nbsp;<code>b</code>&nbsp;is called to be a&nbsp;subarray&nbsp;of&nbsp;<code>a</code>&nbsp;if it forms a contiguous subsequence of&nbsp;<code>a</code>, that is, if it is equal to&nbsp;<code>a[l],a[l+1],...,a[r]</code>&nbsp;for some&nbsp;<code>(l,r)</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,4,5,6]
<strong>Output:</strong> 17
<strong>Explanation:</strong> The optimal subarray here is [2,4,5,6].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,2,1,2,5,2,1,2,5]
<strong>Output:</strong> 8
<strong>Explanation:</strong> The optimal subarray here is [5,2,1] or [1,2,5].
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding window + Hashset</strong></h2>



<p>Maintain a window that has no duplicate elements.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumUniqueSubarray(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    unordered_set&lt;int&gt; t;
    int ans = 0;
    for (int l = 0, r = 0, s = 0; r &lt; n; ++r) {
      while (t.count(nums[r]) &amp;&amp; l &lt; r) {
        s -= nums[l];
        t.erase(nums[l++]);
      }      
      t.insert(nums[r]);
      ans = max(ans, s += nums[r]);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1695-maximum-erasure-value/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1687. Delivering Boxes from Storage to Ports</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1687-delivering-boxes-from-storage-to-ports/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1687-delivering-boxes-from-storage-to-ports/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Dec 2020 09:23:23 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7796</guid>

					<description><![CDATA[You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a&#160;limit&#160;on the&#160;number of boxes&#160;and&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a&nbsp;<strong>limit</strong>&nbsp;on the&nbsp;<strong>number of boxes</strong>&nbsp;and the&nbsp;<strong>total weight</strong>&nbsp;that it can carry.</p>



<p>You are given an array&nbsp;<code>boxes</code>, where&nbsp;<code>boxes[i] = [ports<sub>​​i</sub>​, weight<sub>i</sub>]</code>, and three integers&nbsp;<code>portsCount</code>,&nbsp;<code>maxBoxes</code>, and&nbsp;<code>maxWeight</code>.</p>



<ul class="wp-block-list"><li><code>ports<sub>​​i</sub></code>&nbsp;is the port where you need to deliver the&nbsp;<code>i<sup>th</sup></code>&nbsp;box and&nbsp;<code>weights<sub>i</sub></code>&nbsp;is the weight of the&nbsp;<code>i<sup>th</sup></code>&nbsp;box.</li><li><code>portsCount</code>&nbsp;is the number of ports.</li><li><code>maxBoxes</code>&nbsp;and&nbsp;<code>maxWeight</code>&nbsp;are the respective box and weight limits of the ship.</li></ul>



<p>The boxes need to be delivered&nbsp;<strong>in the order they are given</strong>. The ship will follow these steps:</p>



<ul class="wp-block-list"><li>The ship will take some number of boxes from the&nbsp;<code>boxes</code>&nbsp;queue, not violating the&nbsp;<code>maxBoxes</code>&nbsp;and&nbsp;<code>maxWeight</code>&nbsp;constraints.</li><li>For each loaded box&nbsp;<strong>in order</strong>, the ship will make a&nbsp;<strong>trip</strong>&nbsp;to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no&nbsp;<strong>trip</strong>&nbsp;is needed, and the box can immediately be delivered.</li><li>The ship then makes a return&nbsp;<strong>trip</strong>&nbsp;to storage to take more boxes from the queue.</li></ul>



<p>The ship must end at storage after all the boxes have been delivered.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of&nbsp;<strong>trips</strong>&nbsp;the ship needs to make to deliver all boxes to their respective ports.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> The optimal strategy is as follows: 
- The ship takes all the boxes in the queue, goes to port 1, then port 2, then port 1 again, then returns to storage. 4 trips.
So the total number of trips is 4.
Note that the first and third boxes cannot be delivered together because the boxes need to be delivered in order (i.e. the second box needs to be delivered at port 2 before the third box).
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, maxWeight = 6
<strong>Output:</strong> 6
<strong>Explanation:</strong> The optimal strategy is as follows: 
- The ship takes the first box, goes to port 1, then returns to storage. 2 trips.
- The ship takes the second, third and fourth boxes, goes to port 3, then returns to storage. 2 trips.
- The ship takes the fifth box, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = 6, maxWeight = 7
<strong>Output:</strong> 6
<strong>Explanation:</strong> The optimal strategy is as follows:
- The ship takes the first and second boxes, goes to port 1, then returns to storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 2, then returns to storage. 2 trips.
- The ship takes the fifth and sixth boxes, goes to port 3, then returns to storage. 2 trips.
So the total number of trips is 2 + 2 + 2 = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], portsCount = 5, maxBoxes = 5, maxWeight = 7
<strong>Output:</strong> 14
<strong>Explanation:</strong> The optimal strategy is as follows:
- The ship takes the first box, goes to port 2, then storage. 2 trips.
- The ship takes the second box, goes to port 2, then storage. 2 trips.
- The ship takes the third and fourth boxes, goes to port 3, then storage. 2 trips.
- The ship takes the fifth box, goes to port 3, then storage. 2 trips.
- The ship takes the sixth and seventh boxes, goes to port 3, then port 4, then storage. 3 trips. 
- The ship takes the eighth and ninth boxes, goes to port 1, then port 5, then storage. 3 trips.
So the total number of trips is 2 + 2 + 2 + 2 + 3 + 3 = 14.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= boxes.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= portsCount, maxBoxes, maxWeight &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= ports<sub>​​i</sub>&nbsp;&lt;= portsCount</code></li><li><code>1 &lt;= weights<sub>i</sub>&nbsp;&lt;= maxWeight</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sliding Window</strong></h2>



<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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int boxDelivering(vector&lt;vector&lt;int&gt;&gt;&amp; boxes, int portsCount, int maxBoxes, int maxWeight) {
    const int n = boxes.size();
    vector&lt;int&gt; dp(n + 1); // dp[i] := min trips to deliver boxes[0:i]
    for (int i = 0, j = 0, b = 0, w = 0, t = 1; j &lt; n; ++j) {
      // Different ports.
      if (j == 0 || boxes[j][0] != boxes[j - 1][0]) ++t;      
      // Load the box.
      w += boxes[j][1];
      while (w &gt; maxWeight  // Too heavy.
             || (j - i + 1) &gt; maxBoxes // Too many boxes.
             || (i &lt; j &amp;&amp; dp[i + 1] == dp[i])) { // Same cost more boxes.
        w -= boxes[i++][1]; // 'Unload' the box.
        if (boxes[i][0] != boxes[i - 1][0]) --t; // Different ports.
      }
      // Takes t trips to deliver boxes[i~j].
      dp[j + 1] = dp[i] + t;
    }
    return dp[n];
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1687-delivering-boxes-from-storage-to-ports/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
