<?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>multiset Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/multiset/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/multiset/</link>
	<description></description>
	<lastBuildDate>Thu, 25 Nov 2021 21:18:47 +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>multiset Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/multiset/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2007. Find Original Array From Doubled Array</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2007-find-original-array-from-doubled-array/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2007-find-original-array-from-doubled-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 25 Nov 2021 20:57:49 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[treeset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8766</guid>

					<description><![CDATA[<p>An integer array&#160;original&#160;is transformed into a&#160;doubled&#160;array&#160;changed&#160;by appending&#160;twice the value&#160;of every element in&#160;original, and then randomly&#160;shuffling&#160;the resulting array. Given an array&#160;changed, return&#160;original&#160;if&#160;changed&#160;is a&#160;doubled&#160;array. If&#160;changed&#160;is not a&#160;doubled&#160;array,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2007-find-original-array-from-doubled-array/">花花酱 LeetCode 2007. Find Original Array From Doubled Array</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>An integer array&nbsp;<code>original</code>&nbsp;is transformed into a&nbsp;<strong>doubled</strong>&nbsp;array&nbsp;<code>changed</code>&nbsp;by appending&nbsp;<strong>twice the value</strong>&nbsp;of every element in&nbsp;<code>original</code>, and then randomly&nbsp;<strong>shuffling</strong>&nbsp;the resulting array.</p>



<p>Given an array&nbsp;<code>changed</code>, return&nbsp;<code>original</code><em>&nbsp;if&nbsp;</em><code>changed</code><em>&nbsp;is a&nbsp;<strong>doubled</strong>&nbsp;array. If&nbsp;</em><code>changed</code><em>&nbsp;is not a&nbsp;<strong>doubled</strong>&nbsp;array, return an empty array. The elements in</em>&nbsp;<code>original</code>&nbsp;<em>may be returned in&nbsp;<strong>any</strong>&nbsp;order</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> changed = [1,3,4,2,6,8]
<strong>Output:</strong> [1,3,4]
<strong>Explanation:</strong> One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> changed = [6,3,0,1]
<strong>Output:</strong> []
<strong>Explanation:</strong> changed is not a doubled array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> changed = [1]
<strong>Output:</strong> []
<strong>Explanation:</strong> changed is not a doubled array.
</pre>



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



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



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



<p>Start from the smallest number x, erase one x * 2 from the set.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findOriginalArray(vector&lt;int&gt;&amp; changed) {
    if (changed.size() &amp; 1) return {};
    const int n = changed.size() / 2;
    multiset&lt;int&gt; s(begin(changed), end(changed));    
    while (ans.size() != n) {
      int o = *begin(s);
      s.erase(begin(s));
      ans.push_back(o);
      auto it = s.find(o * 2);
      if (it == end(s)) return {};
      s.erase(it);
    }
    return ans;
  }
};</pre>
</div></div>



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; findOriginalArray(vector&lt;int&gt;&amp; changed) {
    if (changed.size() &amp; 1) return {};
    const int n = changed.size() / 2;
    const int kMax = *max_element(begin(changed), end(changed));
    vector&lt;int&gt; m(kMax + 1);
    for (int x : changed) ++m[x];
    if (m[0] &amp; 1) return {};
    vector&lt;int&gt; ans(m[0] / 2, 0);
    for (int x = 1; ans.size() != n; ++x) {
      if (x * 2 &gt; kMax || m[x * 2] &lt; m[x]) return {};      
      ans.insert(end(ans), m[x], x);
      m[x * 2] -= m[x];   
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2007-find-original-array-from-doubled-array/">花花酱 LeetCode 2007. Find Original Array From Doubled Array</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/hashtable/leetcode-2007-find-original-array-from-doubled-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1825. Finding MK Average</title>
		<link>https://zxi.mytechroad.com/blog/data-structure/leetcode-1825-finding-mk-average/</link>
					<comments>https://zxi.mytechroad.com/blog/data-structure/leetcode-1825-finding-mk-average/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 14 Apr 2021 02:58:09 +0000</pubDate>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[data structure]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[ordered set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8350</guid>

					<description><![CDATA[<p>You are given two integers,&#160;m&#160;and&#160;k, and a stream of integers. You are tasked to implement a data structure that calculates the&#160;MKAverage&#160;for the stream. The&#160;MKAverage&#160;can be&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-1825-finding-mk-average/">花花酱 LeetCode 1825. Finding MK Average</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 integers,&nbsp;<code>m</code>&nbsp;and&nbsp;<code>k</code>, and a stream of integers. You are tasked to implement a data structure that calculates the&nbsp;<strong>MKAverage</strong>&nbsp;for the stream.</p>



<p>The&nbsp;<strong>MKAverage</strong>&nbsp;can be calculated using these steps:</p>



<ol><li>If the number of the elements in the stream is less than&nbsp;<code>m</code>&nbsp;you should consider the&nbsp;<strong>MKAverage</strong>&nbsp;to be&nbsp;<code>-1</code>. Otherwise, copy the last&nbsp;<code>m</code>&nbsp;elements of the stream to a separate container.</li><li>Remove the smallest&nbsp;<code>k</code>&nbsp;elements and the largest&nbsp;<code>k</code>&nbsp;elements from the container.</li><li>Calculate the average value for the rest of the elements&nbsp;<strong>rounded down to the nearest integer</strong>.</li></ol>



<p>Implement the&nbsp;<code>MKAverage</code>&nbsp;class:</p>



<ul><li><code>MKAverage(int m, int k)</code>&nbsp;Initializes the&nbsp;<strong>MKAverage</strong>&nbsp;object with an empty stream and the two integers&nbsp;<code>m</code>&nbsp;and&nbsp;<code>k</code>.</li><li><code>void addElement(int num)</code>&nbsp;Inserts a new element&nbsp;<code>num</code>&nbsp;into the stream.</li><li><code>int calculateMKAverage()</code>&nbsp;Calculates and returns the&nbsp;<strong>MKAverage</strong>&nbsp;for the current stream&nbsp;<strong>rounded down to the nearest integer</strong>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["MKAverage", "addElement", "addElement", "calculateMKAverage", "addElement", "calculateMKAverage", "addElement", "addElement", "addElement", "calculateMKAverage"]
[[3, 1], [3], [1], [], [10], [], [5], [5], [5], []]
<strong>Output</strong>
[null, null, null, -1, null, 3, null, null, null, 5]
<p><strong>Explanation</strong> MKAverage obj = new MKAverage(3, 1); obj.addElement(3); // current elements are [3] obj.addElement(1); // current elements are [3,1] obj.calculateMKAverage(); // return -1, because m = 3 and only 2 elements exist. obj.addElement(10); // current elements are [3,1,10] obj.calculateMKAverage(); // The last 3 elements are [3,1,10]. // After removing smallest and largest 1 element the container will be <code>[3]. // The average of [3] equals 3/1 = 3, return 3 obj.addElement(5); // current elements are [3,1,10,5] obj.addElement(5); // current elements are [3,1,10,5,5] obj.addElement(5); // current elements are [3,1,10,5,5,5] obj.calculateMKAverage(); // The last 3 elements are [5,5,5]. // After removing smallest and largest 1 element the container will be <code>[5]. // The average of [5] equals 5/1 = 5, return 5</code></code></p>
</pre>



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



<ul><li><code>3 &lt;= m &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= k*2 &lt; m</code></li><li><code>1 &lt;= num &lt;= 10<sup>5</sup></code></li><li>At most&nbsp;<code>10<sup>5</sup></code>&nbsp;calls will be made to&nbsp;<code>addElement</code>&nbsp;and&nbsp;<code>calculateMKAverage</code>.</li></ul>



<h2><strong>Solution 1: Multiset * 3</strong></h2>



<p>Use three multiset to track the left part (smallest k elements), right part (largest k elements) and mid (middle part of m &#8211; 2*k elements).</p>



<p>Time complexity: addElememt: O(logn), average: O(1)<br>Space complexity: O(n)</p>



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

<pre class="crayon-plain-tag">class MKAverage {
public:
  MKAverage(int m, int k): 
    sum(0), m(m), k(k), n(m - 2*k) {}

  void addElement(int num) {
    if (q.size() == m) {      
      remove(q.front());
      q.pop();
    }
    q.push(num);
    add(num);
  }

  int calculateMKAverage() {    
    return (q.size() &lt; m) ? -1 : sum / n;
  }
private:
  void add(int x) {
    left.insert(x);
    
    if (left.size() &gt; k) {
      auto it = prev(end(left));
      sum += *it;
      mid.insert(*it);      
      left.erase(it);
    }
    
    if (mid.size() &gt; n) {
      auto it = prev(end(mid));
      sum -= *it; 
      right.insert(*it);
      mid.erase(it);
    }
  }
  
  void remove(int x) {
    if (x &lt;= *rbegin(left)) {
      left.erase(left.find(x));
    } else if (x &lt;= *rbegin(mid)) {
      sum -= x;
      mid.erase(mid.find(x));
    } else {
      right.erase(right.find(x));
    }
    
    if (left.size() &lt; k) {
      auto it = begin(mid);
      sum -= *it;
      left.insert(*it);
      mid.erase(it);
    }
    
    if (mid.size() &lt; n) {
      auto it = begin(right);
      sum += *it;
      mid.insert(*it);
      right.erase(it);
    }
  }
  
  queue&lt;int&gt; q;
  multiset&lt;int&gt; left, mid, right;  
  long sum;
  const int m;
  const int k;
  const int n;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/data-structure/leetcode-1825-finding-mk-average/">花花酱 LeetCode 1825. Finding MK Average</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/data-structure/leetcode-1825-finding-mk-average/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</title>
		<link>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/</link>
					<comments>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 04 May 2020 04:21:37 +0000</pubDate>
				<category><![CDATA[Queue]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[monotonic queue]]></category>
		<category><![CDATA[multiset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6701</guid>

					<description><![CDATA[<p>Given an&#160;array of integers&#160;nums&#160;and an&#160;integer&#160;limit, return the size of the longest continuous subarray such that the absolute difference between any two elements is less than&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/">花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit EP323" width="500" height="375" src="https://www.youtube.com/embed/p8-f0_CwWLk?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an&nbsp;array of integers&nbsp;<code>nums</code>&nbsp;and an&nbsp;integer&nbsp;<code>limit</code>, return the size of the longest continuous subarray such that the absolute difference between any two elements is less than or equal to&nbsp;<code>limit</code><em>.</em></p>



<p>In case there is no subarray satisfying the given condition return 0.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [8,2,4,7], limit = 4
<strong>Output:</strong> 2 
<strong>Explanation:</strong> All subarrays are: 
[8] with maximum absolute diff |8-8| = 0 &lt;= 4.
[8,2] with maximum absolute diff |8-2| = 6 &gt; 4. 
[8,2,4] with maximum absolute diff |8-2| = 6 &gt; 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 &gt; 4.
[2] with maximum absolute diff |2-2| = 0 &lt;= 4.
[2,4] with maximum absolute diff |2-4| = 2 &lt;= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 &gt; 4.
[4] with maximum absolute diff |4-4| = 0 &lt;= 4.
[4,7] with maximum absolute diff |4-7| = 3 &lt;= 4.
[7] with maximum absolute diff |7-7| = 0 &lt;= 4. 
Therefore, the size of the longest subarray is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,1,2,4,7,2], limit = 5
<strong>Output:</strong> 4 
<strong>Explanation:</strong> The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 &lt;= 5.
</pre>



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



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



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



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



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



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



<h2><strong>Solution 1: Sliding Window + TreeSet</strong></h2>



<p>Use a treeset to maintain a range of [l, r] such that max(nums[l~r]) &#8211; min(nums[l~r]) &lt;= limit.<br>Every time, we add nums[r] into the tree, and move l towards r to keep the max diff under limit.</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 longestSubarray(vector&lt;int&gt;&amp; nums, int limit) {
    multiset&lt;int&gt; s;
    int l = 0;
    int ans = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      s.insert(nums[r]);
      while (*rbegin(s) - *begin(s) &gt; limit)
        s.erase(s.equal_range(nums[l++]).first);
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>



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



<p>Similar to <a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/">https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1425-constrained-subset-sum/</a></p>



<p>We want to maintain a range [l, r] that max(nums[l~r]) &#8211; min(nums[l~r]) &lt;= limit, to track the max/min of a range efficiently we could use monotonic queue. One for max and one for min.</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:
  int longestSubarray(vector&lt;int&gt;&amp; nums, int limit) {
    deque&lt;int&gt; max_q;
    deque&lt;int&gt; min_q;
    int ans = 0;
    int l = 0;
    for (int r = 0; r &lt; nums.size(); ++r) {
      while (!min_q.empty() &amp;&amp; nums[r] &lt; min_q.back()) 
        min_q.pop_back();
      while (!max_q.empty() &amp;&amp; nums[r] &gt; max_q.back()) 
        max_q.pop_back();
      min_q.push_back(nums[r]);
      max_q.push_back(nums[r]);
      while (max_q.front() - min_q.front() &gt; limit) {
        if (max_q.front() == nums[l]) max_q.pop_front();
        if (min_q.front() == nums[l]) min_q.pop_front();
        ++l;
      }
      ans = max(ans, r - l + 1);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/">花花酱 LeetCode 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/queue/leetcode-1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 220. Contains Duplicate III</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-220-contains-duplicate-iii/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-220-contains-duplicate-iii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 21 Dec 2018 05:55:24 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sorted]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4515</guid>

					<description><![CDATA[<p>Given an array of integers, find out whether there are two distinct indices&#160;i&#160;and&#160;j&#160;in the array such that the&#160;absolute&#160;difference between&#160;nums[i]&#160;and&#160;nums[j]&#160;is at most&#160;t&#160;and the&#160;absolute&#160;difference between&#160;i&#160;and&#160;j&#160;is at most&#160;k.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-220-contains-duplicate-iii/">花花酱 LeetCode 220. Contains Duplicate III</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers, find out whether there are two distinct indices&nbsp;<em>i</em>&nbsp;and&nbsp;<em>j</em>&nbsp;in the array such that the&nbsp;<strong>absolute</strong>&nbsp;difference between&nbsp;<strong>nums[i]</strong>&nbsp;and&nbsp;<strong>nums[j]</strong>&nbsp;is at most&nbsp;<em>t</em>&nbsp;and the&nbsp;<strong>absolute</strong>&nbsp;difference between&nbsp;<em>i</em>&nbsp;and&nbsp;<em>j</em>&nbsp;is at most&nbsp;<em>k</em>.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>nums = [1,2,3,1], k = 3, t = 0<br><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, t = 2<br><strong>Output: </strong>true</pre>



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



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



<h1><strong>Solution: Sliding Window + Multiset (OrderedSet)</strong></h1>



<p>Maintaining a sliding window of sorted numbers of k + 1. After the i-th number was inserted into the sliding window, check whether its left and right neighbors satisfy abs(nums[i] &#8211; neighbor) &lt;= t</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua, running time: 12 ms
class Solution {
public:
  bool containsNearbyAlmostDuplicate(vector&lt;int&gt;&amp; nums, int k, int t) {
    multiset&lt;long&gt; s;
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (i &gt; k)
        s.erase(s.find(nums[i - k - 1]));
            
      auto it = s.insert(nums[i]);
      if (it != begin(s) &amp;&amp; *it - *prev(it) &lt;= t)
        return true;
      if (next(it) != end(s) &amp;&amp; *next(it) - *it &lt;= t)
        return true;
    }
    return false;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-220-contains-duplicate-iii/">花花酱 LeetCode 220. Contains Duplicate III</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/hashtable/leetcode-220-contains-duplicate-iii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 502. IPO</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-502-ipo/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-502-ipo/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Aug 2018 03:03:21 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[priority queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3429</guid>

					<description><![CDATA[<p>Problem Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-502-ipo/">花花酱 LeetCode 502. IPO</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Suppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the IPO. Since it has limited resources, it can only finish at most <b>k</b> distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most <b>k</b> distinct projects.</p>
<p>You are given several projects. For each project <b>i</b>, it has a pure profit <b>P<sub>i</sub></b> and a minimum capital of <b>C<sub>i</sub></b> is needed to start the corresponding project. Initially, you have <b>W</b> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p>
<p>To sum up, pick a list of at most <b>k</b> distinct projects from given projects to maximize your final capital, and output your final maximized capital.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> k=2, W=0, Profits=[1,2,3], Capital=[0,1,1].

<b>Output:</b> 4

<b>Explanation:</b> Since your initial capital is 0, you can only start the project indexed 0.
             After finishing it you will obtain profit 1 and your capital becomes 1.
             With capital 1, you can either start the project indexed 1 or the project indexed 2.
             Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
             Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
</pre>
<p><b>Note:</b></p>
<ol>
<li>You may assume all numbers in the input are non-negative integers.</li>
<li>The length of Profits array and Capital array will not exceed 50,000.</li>
<li>The answer is guaranteed to fit in a 32-bit signed integer.</li>
</ol>
<h1><strong>Solution: Greedy</strong></h1>
<p>For each round, find the most profitable job whose capital requirement &lt;= W.</p>
<p>Finish that job and increase W.</p>
<p>Brute force (TLE)</p>
<p>Time complexity: O(kn)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="crayon-plain-tag">class Solution {
public:
  int findMaximizedCapital(int k, int W, vector&lt;int&gt;&amp; Profits, vector&lt;int&gt;&amp; Capital) {
    for (int i = 0; i &lt; k; ++i) {
      int best_j = -1;
      int best_profit = 0;
      for (int j = 0; j &lt; Profits.size(); ++j) {
        if (Capital[j] &lt;= W &amp;&amp; Profits[j] &gt; best_profit) {
          best_j = j;
          best_profit = Profits[j];
        }
      }
      if (best_profit == 0) break;
      W += Profits[best_j];
      Profits[best_j] = INT_MIN; // Used.
    }
    return W;
  }
};</pre><p>Use priority queue and multiset to track doable and undoable projects at given W.</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms (beats 96.4%)
class Solution {
public:
  int findMaximizedCapital(int k, int W, vector&lt;int&gt;&amp; Profits, vector&lt;int&gt;&amp; Capital) {    
    priority_queue&lt;int&gt; doable;         // sorted by profit high to low.
    multiset&lt;pair&lt;int, int&gt;&gt; undoable;  // {capital, profit}
    for (int i = 0; i &lt; Profits.size(); ++i) {
      if (Profits[i] &lt;= 0) continue;
      if (Capital[i] &lt;= W) 
        doable.push(Profits[i]);
      else
        undoable.emplace(Capital[i], Profits[i]);
    }
    auto it = undoable.cbegin();
    while (!doable.empty() &amp;&amp; k--) {
      W += doable.top(); doable.pop();      
      while (it != undoable.cend() &amp;&amp; it-&gt;first &lt;= W)
        doable.push(it++-&gt;second);      
    }
    return W;
  }
};</pre><p>Or use an array and sort by capital</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 28 ms (beats 96.4%)
class Solution {
public:
  int findMaximizedCapital(int k, int W, vector&lt;int&gt;&amp; Profits, vector&lt;int&gt;&amp; Capital) {    
    priority_queue&lt;int&gt; doable;         // sorted by profit high to low.
    vector&lt;pair&lt;int, int&gt;&gt; undoable;    // {capital, profit}
    for (int i = 0; i &lt; Profits.size(); ++i) {
      if (Profits[i] &lt;= 0) continue;
      if (Capital[i] &lt;= W) 
        doable.push(Profits[i]);
      else
        undoable.emplace_back(Capital[i], Profits[i]);
    }
    sort(begin(undoable), end(undoable));
    auto it = undoable.cbegin();
    while (!doable.empty() &amp;&amp; k--) {
      W += doable.top(); doable.pop();      
      while (it != undoable.cend() &amp;&amp; it-&gt;first &lt;= W)
        doable.push(it++-&gt;second);      
    }
    return W;
  }
};</pre><p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-502-ipo/">花花酱 LeetCode 502. IPO</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-502-ipo/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 870. Advantage Shuffle</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-870-advantage-shuffle/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-870-advantage-shuffle/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Jul 2018 05:43:37 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[inversion]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[multiset]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3168</guid>

					<description><![CDATA[<p>Problem Given two arrays A and B of equal size, the advantage of A with respect to B is the number of indices i for which A[i] &#62; B[i]. Return any permutation of A that maximizes its advantage with respect to B.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-870-advantage-shuffle/">花花酱 LeetCode 870. Advantage Shuffle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given two arrays <code>A</code> and <code>B</code> of equal size, the <em>advantage of <code>A</code> with respect to <code>B</code></em> is the number of indices <code>i</code> for which <code>A[i] &gt; B[i]</code>.</p>
<p>Return <strong>any</strong> permutation of <code>A</code> that maximizes its advantage with respect to <code>B</code>.</p>
<div>
<p><strong>Example 1:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>A = <span id="example-input-1-1">[2,7,11,15]</span>, B = <span id="example-input-1-2">[1,10,4,11]</span>
<strong>Output: </strong><span id="example-output-1">[2,11,7,15]</span>
</pre>
<div>
<p><strong>Example 2:</strong></p>
<pre class="crayon:false"><strong>Input: </strong>A = <span id="example-input-2-1">[12,24,8,32]</span>, B = <span id="example-input-2-2">[13,25,32,11]</span>
<strong>Output: </strong><span id="example-output-2">[24,32,8,12]</span>
</pre>
<p><strong>Note:</strong></p>
<ol>
<li><code>1 &lt;= A.length = B.length &lt;= 10000</code></li>
<li><code>0 &lt;= A[i] &lt;= 10^9</code></li>
<li><code>0 &lt;= B[i] &lt;= 10^9</code></li>
</ol>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"> </ins></p>
<h1><strong>Solution: Greedy 田忌赛马</strong></h1>
<p>Use the smallest unused number A[j] in A such that A[j] &gt; B[i], if not possible, use the smallest number in A.</p>
<p>Time complexity: O(nlogn)</p>
<p>Space complexity: O(n)</p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 124 ms
class Solution {
public:
  vector&lt;int&gt; advantageCount(vector&lt;int&gt;&amp; A, vector&lt;int&gt;&amp; B) {
    multiset&lt;int&gt; s(begin(A), end(A));
    vector&lt;int&gt; ans;    
    for (int b : B) {
      auto it = s.upper_bound(b);
      if (it == s.end()) it = s.begin();      
      ans.push_back(*it);
      s.erase(it);
    }
    return ans;
  }
};</pre><p>&nbsp;</p>
</div>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-870-advantage-shuffle/">花花酱 LeetCode 870. Advantage Shuffle</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-870-advantage-shuffle/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
