<?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>Binary Search Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/category/algorithms/binary-search/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/category/algorithms/binary-search/</link>
	<description></description>
	<lastBuildDate>Sun, 05 Feb 2023 17:13:09 +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>Binary Search Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/category/algorithms/binary-search/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2560. House Robber IV</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2560-house-robber-iv/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2560-house-robber-iv/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Feb 2023 05:47:10 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9932</guid>

					<description><![CDATA[<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2560-house-robber-iv/">花花酱 LeetCode 2560. House Robber IV</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 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 2560. House Robber IV - 刷题找工作 EP409" width="500" height="281" src="https://www.youtube.com/embed/DulvOfbAdzI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div></figure>



<p>There are several consecutive houses along a street, each of which has some money inside. There is also a robber, who wants to steal money from the homes, but he&nbsp;<strong>refuses to steal from adjacent homes</strong>.</p>



<p>The&nbsp;<strong>capability</strong>&nbsp;of the robber is the maximum amount of money he steals from one house of all the houses he robbed.</p>



<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;representing how much money is stashed in each house. More formally, the&nbsp;<code>i<sup>th</sup></code>&nbsp;house from the left has&nbsp;<code>nums[i]</code>&nbsp;dollars.</p>



<p>You are also given an integer&nbsp;<code>k</code>, representing the&nbsp;<strong>minimum</strong>&nbsp;number of houses the robber will steal from.&nbsp;It is always possible to steal at least&nbsp;<code>k</code>&nbsp;houses.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;</em>capability of the robber out of all the possible ways to steal at least&nbsp;<code>k</code>&nbsp;houses.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,5,9], k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> 
There are three ways to rob at least 2 houses:
- Rob the houses at indices 0 and 2. Capability is max(nums[0], nums[2]) = 5.
- Rob the houses at indices 0 and 3. Capability is max(nums[0], nums[3]) = 9.
- Rob the houses at indices 1 and 3. Capability is max(nums[1], nums[3]) = 9.
Therefore, we return min(5, 9, 9) = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,7,9,3,1], k = 2
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are 7 ways to rob the houses. The way which leads to minimum capability is to rob the house at index 0 and 4. Return max(nums[0], nums[4]) = 2.
</pre>



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



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



<h2><strong>Solution 1: Binary Search + DP</strong></h2>



<p>It&#8217;s easy to see that higher capability means more houses we can rob. Thus this can be formulate as a binary search algorithm e.g. find the minimum C s.t. we can rob at least k houses.</p>



<p>Then we can use dp(i) to calculate maximum houses we can rob if starting from the i&#8217;th house.<br>dp(i) = max(1 + dp(i + 2) if nums[i] &lt;= C else 0, dp(i + 1))</p>



<p>Time complexity: O(n log m)<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 minCapability(vector&lt;int&gt;&amp; nums, int k) {
    int l = 0;
    int r = *max_element(begin(nums), end(nums)) + 1;
    vector&lt;int&gt; cache(nums.size(), -1);
    function&lt;int(int, int)&gt; rob = [&amp;](int m, int i) -&gt; int {
      if (i &gt;= nums.size()) return 0;
      if (cache[i] &gt;= 0) return cache[i];
      if (nums[i] &gt; m) return rob(m, i + 1);
      return cache[i] = max(1 + rob(m, i + 2), rob(m, i + 1));
    };
    while (l &lt; r) {
      int m = l + (r - l) / 2;
      fill(begin(cache), end(cache), -1);
      if (rob(m, 0) &gt;= k)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Binary Search + Greedy</strong></h2>



<p>From: dp(i) = max(1 + dp(i + 2) if nums[i] &lt;= C else 0, dp(i + 1)) we can see that if we can pick the i-th one, it will be the same or better if we skip and start from dp(i + 1). Thus we can convert this from DP to greedy. As long as we can pick the current one, we pick it first.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minCapability(vector&lt;int&gt;&amp; nums, int k) {
    int l = 0;
    int r = *max_element(begin(nums), end(nums)) + 1;    
    auto rob = [&amp;](int m) -&gt; int {
      int ans = 0;
      for (int i = 0; i &lt; nums.size(); ++i)
        if (nums[i] &lt;= m) {
          ++ans;
          ++i;
        }
      return ans;
    };
    while (l &lt; r) {
      int m = l + (r - l) / 2;      
      if (rob(m) &gt;= k)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2560-house-robber-iv/">花花酱 LeetCode 2560. House Robber IV</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2560-house-robber-iv/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search Tree</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 22 Nov 2022 00:28:58 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[BST]]></category>
		<category><![CDATA[lower_bound]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<category><![CDATA[upper_bound]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9889</guid>

					<description><![CDATA[<p>You are given the&#160;root&#160;of a&#160;binary search tree&#160;and an array&#160;queries&#160;of size&#160;n&#160;consisting of positive integers. Find a&#160;2D&#160;array&#160;answer&#160;of size&#160;n&#160;where&#160;answer[i] = [mini, maxi]: mini&#160;is the&#160;largest&#160;value in the tree that&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/">花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search Tree</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 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 2476. Closest Nodes Queries in a Binary Search Tree - 刷题找工作 EP405" width="500" height="281" src="https://www.youtube.com/embed/UZYgQLMyocw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>You are given the&nbsp;<code>root</code>&nbsp;of a&nbsp;<strong>binary search tree&nbsp;</strong>and an array&nbsp;<code>queries</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;consisting of positive integers.</p>



<p>Find a&nbsp;<strong>2D</strong>&nbsp;array&nbsp;<code>answer</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;where&nbsp;<code>answer[i] = [min<sub>i</sub>, max<sub>i</sub>]</code>:</p>



<ul><li><code>min<sub>i</sub></code>&nbsp;is the&nbsp;<strong>largest</strong>&nbsp;value in the tree that is smaller than or equal to&nbsp;<code>queries[i]</code>. If a such value does not exist, add&nbsp;<code>-1</code>&nbsp;instead.</li><li><code>max<sub>i</sub></code>&nbsp;is the&nbsp;<strong>smallest</strong>&nbsp;value in the tree that is greater than or equal to&nbsp;<code>queries[i]</code>. If a such value does not exist, add&nbsp;<code>-1</code>&nbsp;instead.</li></ul>



<p>Return&nbsp;<em>the array</em>&nbsp;<code>answer</code>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/28/bstreeedrawioo.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]
<strong>Output:</strong> [[2,2],[4,6],[15,-1]]
<strong>Explanation:</strong> We answer the queries in the following way:
- The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2].
- The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6].
- The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/09/28/bstttreee.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> root = [4,null,9], queries = [3]
<strong>Output:</strong> [[-1,4]]
<strong>Explanation:</strong> The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].
</pre>



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



<ul><li>The number of nodes in the tree is in the range&nbsp;<code>[2, 10<sup>5</sup>]</code>.</li><li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li><li><code>n == queries.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= queries[i] &lt;= 10<sup>6</sup></code></li></ul>



<h2><strong>Solution: Convert to sorted array</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png" alt="" class="wp-image-9898" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png" alt="" class="wp-image-9899" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png" alt="" class="wp-image-9900" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s3-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png" alt="" class="wp-image-9901" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/11/2476-ep405-s4-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Since we don&#8217;t know whether the tree is balanced or not, the safest and easiest way is to convert the tree into a sorted array using inorder traversal. Or just any traversal and sort the array later on.</p>



<p>Once we have a sorted array, we can use lower_bound / upper_bound to query.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; closestNodes(TreeNode* root, vector&lt;int&gt;&amp; queries) {    
    vector&lt;int&gt; vals;
    function&lt;void(TreeNode*)&gt; inorder = [&amp;](TreeNode* root) {
      if (!root) return;
      inorder(root-&gt;left);
      vals.push_back(root-&gt;val);
      inorder(root-&gt;right);
    };
    
    inorder(root);
    
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const int q : queries) {
      vector&lt;int&gt; cur{-1, -1};
      auto lit = upper_bound(begin(vals), end(vals), q);
      if (lit != begin(vals))
        cur[0] = *(prev(lit));
      auto rit = lower_bound(begin(vals), end(vals), q);
      if (rit != end(vals))
        cur[1] = *rit;      
      ans.push_back(std::move(cur));
    }
    return ans;
  }
};</pre>
</div></div>



<p>One binary search per query.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;vector&lt;int&gt;&gt; closestNodes(TreeNode* root, vector&lt;int&gt;&amp; queries) {    
    vector&lt;int&gt; vals;
    function&lt;void(TreeNode*)&gt; inorder = [&amp;](TreeNode* root) {
      if (!root) return;
      inorder(root-&gt;left);
      if (vals.empty() || root-&gt;val &gt; vals.back()) vals.push_back(root-&gt;val);
      inorder(root-&gt;right);
    };
    
    inorder(root);
    
    vector&lt;vector&lt;int&gt;&gt; ans;
    for (const int q : queries) {
      vector&lt;int&gt; cur{-1, -1};      
      auto it = lower_bound(begin(vals), end(vals), q);
      if (it != end(vals) &amp;&amp; *it == q)
        cur[0] = cur[1] = q;
      else {
        if (it != begin(vals)) cur[0] = *prev(it);
        if (it != end(vals)) cur[1] = *it;        
      }
      ans.push_back(std::move(cur));
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/">花花酱 LeetCode 2476. Closest Nodes Queries in a Binary Search Tree</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2476-closest-nodes-queries-in-a-binary-search-tree/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2389. Longest Subsequence With Limited Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 01 Sep 2022 12:04:07 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9791</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;of length&#160;n, and an integer array&#160;queries&#160;of length&#160;m. Return&#160;an array&#160;answer&#160;of length&#160;m&#160;where&#160;answer[i]&#160;is the&#160;maximum&#160;size of a&#160;subsequence&#160;that you can take from&#160;nums&#160;such that the&#160;sum&#160;of its&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/">花花酱 LeetCode 2389. Longest Subsequence With Limited Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>, and an integer array&nbsp;<code>queries</code>&nbsp;of length&nbsp;<code>m</code>.</p>



<p>Return&nbsp;<em>an array&nbsp;</em><code>answer</code><em>&nbsp;of length&nbsp;</em><code>m</code><em>&nbsp;where&nbsp;</em><code>answer[i]</code><em>&nbsp;is the&nbsp;<strong>maximum</strong>&nbsp;size of a&nbsp;<strong>subsequence</strong>&nbsp;that you can take from&nbsp;</em><code>nums</code><em>&nbsp;such that the&nbsp;<strong>sum</strong>&nbsp;of its elements is less than or equal to&nbsp;</em><code>queries[i]</code>.</p>



<p>A&nbsp;<strong>subsequence</strong>&nbsp;is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,5,2,1], queries = [3,10,21]
<strong>Output:</strong> [2,3,4]
<strong>Explanation:</strong> We answer the queries as follows:
- The subsequence [2,1] has a sum less than or equal to 3. It can be proven that 2 is the maximum size of such a subsequence, so answer[0] = 2.
- The subsequence [4,5,1] has a sum less than or equal to 10. It can be proven that 3 is the maximum size of such a subsequence, so answer[1] = 3.
- The subsequence [4,5,2,1] has a sum less than or equal to 21. It can be proven that 4 is the maximum size of such a subsequence, so answer[2] = 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,4,5], queries = [1]
<strong>Output:</strong> [0]
<strong>Explanation:</strong> The empty subsequence is the only subsequence that has a sum less than or equal to 1, so answer[0] = 0.</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>m == queries.length</code></li><li><code>1 &lt;= n, m &lt;= 1000</code></li><li><code>1 &lt;= nums[i], queries[i] &lt;= 10<sup>6</sup></code></li></ul>



<h2><strong>Solution: Sort + PrefixSum + Binary Search</strong></h2>



<p>Time complexity: O(nlogn + mlogn)<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; answerQueries(vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; queries) {    
    sort(begin(nums), end(nums));
    partial_sum(begin(nums), end(nums), begin(nums));
    vector&lt;int&gt; ans;
    for (int q : queries)
      ans.push_back(upper_bound(begin(nums), end(nums), q) - begin(nums));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/">花花酱 LeetCode 2389. Longest Subsequence With Limited Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2226. Maximum Candies Allocated to K Children</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2226-maximum-candies-allocated-to-k-children/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2226-maximum-candies-allocated-to-k-children/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Apr 2022 06:08:13 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9623</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;candies. Each element in the array denotes a pile of candies of size&#160;candies[i]. You can divide each pile into any number&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2226-maximum-candies-allocated-to-k-children/">花花酱 LeetCode 2226. Maximum Candies Allocated to K Children</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>candies</code>. Each element in the array denotes a pile of candies of size&nbsp;<code>candies[i]</code>. You can divide each pile into any number of&nbsp;<strong>sub piles</strong>, but you&nbsp;<strong>cannot</strong>&nbsp;merge two piles together.</p>



<p>You are also given an integer&nbsp;<code>k</code>. You should allocate piles of candies to&nbsp;<code>k</code>&nbsp;children such that each child gets the&nbsp;<strong>same</strong>&nbsp;number of candies. Each child can take&nbsp;<strong>at most one</strong>&nbsp;pile of candies and some piles of candies may go unused.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum number of candies</strong>&nbsp;each child can get.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> candies = [5,8,6], k = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> candies = [2,5], k = 11
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.
</pre>



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



<ul><li><code>1 &lt;= candies.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= candies[i] &lt;= 10<sup>7</sup></code></li><li><code>1 &lt;= k &lt;= 10<sup>12</sup></code></li></ul>



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



<p>Find the smallest L s.t. we can allocate candies to less than k children.</p>



<p>ans = L &#8211; 1.</p>



<p>Time complexity: O(nlogm) where n is number of piles, m is sum(candies) / k.<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumCandies(vector&lt;int&gt;&amp; candies, long long k) {
    long long total = accumulate(begin(candies), end(candies), 0LL);
    long long l = 1;
    long long r = total / k + 1;
    while (l &lt; r) {
      long long m = l + (r - l) / 2;
      long long c = 0;
      for (int pile : candies)
        c += pile / m;
      if (c &lt; k)
        r = m;
      else
        l = m + 1;
    }
    return l - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2226-maximum-candies-allocated-to-k-children/">花花酱 LeetCode 2226. Maximum Candies Allocated to K Children</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2226-maximum-candies-allocated-to-k-children/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2187. Minimum Time to Complete Trips</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2187-minimum-time-to-complete-trips/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2187-minimum-time-to-complete-trips/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Feb 2022 13:03:25 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9512</guid>

					<description><![CDATA[<p>You are given an array&#160;time&#160;where&#160;time[i]&#160;denotes the time taken by the&#160;ith&#160;bus to complete&#160;one trip. Each bus can make multiple trips&#160;successively; that is, the next trip can&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2187-minimum-time-to-complete-trips/">花花酱 LeetCode 2187. Minimum Time to Complete Trips</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given an array&nbsp;<code>time</code>&nbsp;where&nbsp;<code>time[i]</code>&nbsp;denotes the time taken by the&nbsp;<code>i<sup>th</sup></code>&nbsp;bus to complete&nbsp;<strong>one trip</strong>.</p>



<p>Each bus can make multiple trips&nbsp;<strong>successively</strong>; that is, the next trip can start&nbsp;<strong>immediately after</strong>&nbsp;completing the current trip. Also, each bus operates&nbsp;<strong>independently</strong>; that is, the trips of one bus do not influence the trips of any other bus.</p>



<p>You are also given an integer&nbsp;<code>totalTrips</code>, which denotes the number of trips all buses should make&nbsp;<strong>in total</strong>. Return&nbsp;<em>the&nbsp;<strong>minimum time</strong>&nbsp;required for all buses to complete&nbsp;<strong>at least</strong>&nbsp;</em><code>totalTrips</code><em>&nbsp;trips</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> time = [1,2,3], totalTrips = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong>
- At time t = 1, the number of trips completed by each bus are [1,0,0]. 
  The total number of trips completed is 1 + 0 + 0 = 1.
- At time t = 2, the number of trips completed by each bus are [2,1,0]. 
  The total number of trips completed is 2 + 1 + 0 = 3.
- At time t = 3, the number of trips completed by each bus are [3,1,1]. 
  The total number of trips completed is 3 + 1 + 1 = 5.
So the minimum time needed for all buses to complete at least 5 trips is 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> time = [2], totalTrips = 1
<strong>Output:</strong> 2
<strong>Explanation:</strong>
There is only one bus, and it will complete its first trip at t = 2.
So the minimum time needed to complete 1 trip is 2.
</pre>



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



<ul><li><code>1 &lt;= time.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= time[i], totalTrips &lt;= 10<sup>7</sup></code></li></ul>



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



<p>Find the smallest t s.t. trips &gt;= totalTrips.</p>



<p>Time complexity: O(nlogm), where m ~= 1e15<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimumTime(vector&lt;int&gt;&amp; time, int totalTrips) {
    long long l = 1;
    long long r = 1e15;
    while (l &lt; r) {
      long long m = l + (r - l) / 2;
      long long trips = 0;
      for (int t : time) {        
        trips += m / t;
        if (trips &gt;= totalTrips) break;
      }
      if (trips &gt;= totalTrips)
        r = m;
      else
        l = m + 1;
    }
    return l;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2187-minimum-time-to-complete-trips/">花花酱 LeetCode 2187. Minimum Time to Complete Trips</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2187-minimum-time-to-complete-trips/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2141. Maximum Running Time of N Computers</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2141-maximum-running-time-of-n-computers/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2141-maximum-running-time-of-n-computers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 31 Jan 2022 00:28:09 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[gready]]></category>
		<category><![CDATA[hard]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9446</guid>

					<description><![CDATA[<p>You have&#160;n&#160;computers. You are given the integer&#160;n&#160;and a&#160;0-indexed&#160;integer array&#160;batteries&#160;where the&#160;ith&#160;battery can&#160;run&#160;a computer for&#160;batteries[i]&#160;minutes. You are interested in running&#160;all&#160;n&#160;computers&#160;simultaneously&#160;using the given batteries. Initially, you can insert&#160;at&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2141-maximum-running-time-of-n-computers/">花花酱 LeetCode 2141. Maximum Running Time of N Computers</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 have&nbsp;<code>n</code>&nbsp;computers. You are given the integer&nbsp;<code>n</code>&nbsp;and a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>batteries</code>&nbsp;where the&nbsp;<code>i<sup>th</sup></code>&nbsp;battery can&nbsp;<strong>run</strong>&nbsp;a computer for&nbsp;<code>batteries[i]</code>&nbsp;minutes. You are interested in running&nbsp;<strong>all</strong>&nbsp;<code>n</code>&nbsp;computers&nbsp;<strong>simultaneously</strong>&nbsp;using the given batteries.</p>



<p>Initially, you can insert&nbsp;<strong>at most one battery</strong>&nbsp;into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery&nbsp;<strong>any number of times</strong>. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time.</p>



<p>Note that the batteries cannot be recharged.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of minutes you can run all the&nbsp;</em><code>n</code><em>&nbsp;computers simultaneously.</em></p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/01/06/example1-fit.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, batteries = [3,3,3]
<strong>Output:</strong> 4
<strong>Explanation:</strong> 
Initially, insert battery 0 into the first computer and battery 1 into the second computer.
After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute.
At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead.
By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running.
We can run the two computers simultaneously for at most 4 minutes, so we return 4.

</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2022/01/06/example2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, batteries = [1,1,1,1]
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
Initially, insert battery 0 into the first computer and battery 2 into the second computer. 
After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. 
After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running.
We can run the two computers simultaneously for at most 2 minutes, so we return 2.
</pre>



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



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



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



<p>Find the smallest L that we can not run, ans = L &#8211; 1.</p>



<p>For a guessing m, we check the total battery powers T = sum(min(m, batteries[i])), if T >= m * n, it means there is a way (doesn&#8217;t need to figure out how) to run n computers for m minutes by fully unitize those batteries.</p>



<p>Proof: If T >= m*n holds, there are two cases:</p>



<ol><li>There are only n batteries, can not swap, but each of them has power >= m.</li><li>At least one of the batteries have power less than m, but there are more than n batteries and total power is sufficient, we can swap them with others.</li></ol>



<p>Time complexity: O(Slogn) where S = sum(batteries)<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  long long maxRunTime(int n, vector&lt;int&gt;&amp; batteries) {
    long long l = 0;
    long long r = accumulate(begin(batteries), end(batteries), 0LL) + 1;
    while (l &lt; r) {
      long long m = l + (r - l) / 2;
      long long t = 0;
      for (long long b : batteries)
        t += min(m, b);
      if (m * n &gt; t) // smallest m that does not fit.
        r = m;
      else
        l = m + 1;
    }
    return l - 1; // greatest m that fits.
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2141-maximum-running-time-of-n-computers/">花花酱 LeetCode 2141. Maximum Running Time of N Computers</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2141-maximum-running-time-of-n-computers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1995. Count Special Quadruplets</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1995-count-special-quadruplets/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1995-count-special-quadruplets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 02:10:44 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9375</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums, return&#160;the number of&#160;distinct&#160;quadruplets&#160;(a, b, c, d)&#160;such that: nums[a] + nums[b] + nums[c] == nums[d], and a &#60; b &#60; c &#60; d&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1995-count-special-quadruplets/">花花酱 LeetCode 1995. Count Special Quadruplets</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, return&nbsp;<em>the number of&nbsp;<strong>distinct</strong>&nbsp;quadruplets</em>&nbsp;<code>(a, b, c, d)</code>&nbsp;<em>such that:</em></p>



<ul><li><code>nums[a] + nums[b] + nums[c] == nums[d]</code>, and</li><li><code>a &lt; b &lt; c &lt; d</code></li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,6]
<strong>Output:</strong> 1
<strong>Explanation:</strong> The only quadruplet that satisfies the requirement is (0, 1, 2, 3) because 1 + 2 + 3 == 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,3,6,4,5]
<strong>Output:</strong> 0
<strong>Explanation:</strong> There are no such quadruplets in [3,3,6,4,5].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1,3,5]
<strong>Output:</strong> 4
<strong>Explanation:</strong> The 4 quadruplets that satisfy the requirement are:
- (0, 1, 2, 3): 1 + 1 + 1 == 3
- (0, 1, 3, 4): 1 + 1 + 3 == 5
- (0, 2, 3, 4): 1 + 1 + 3 == 5
- (1, 2, 3, 4): 1 + 1 + 3 == 5
</pre>



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



<ul><li><code>4 &lt;= nums.length &lt;= 50</code></li><li><code>1 &lt;= nums[i] &lt;= 100</code></li></ul>



<h2><strong>Solution 1: Brute force (224ms</strong>)</h2>



<p>Enumerate a, b, c, d.</p>



<p>Time complexity: O(C(n, 4)) = O(n<sup>4</sup>/24)<br>Space complexity: O(1)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countQuadruplets(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    int ans = 0;
    for (int a = 0; a &lt; n; ++a)
      for (int b = a + 1; b &lt; n; ++b)
        for (int c = b + 1; c &lt; n; ++c)
          for (int d = c + 1; d &lt; n; ++d)
            ans += nums[a] + nums[b] + nums[c] == nums[d];
    return ans;
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Static <meta charset="utf-8"><strong>frequency table</strong> + binary search (39ms)</strong></h2>



<p>For each element, we store its indices (sorted).</p>



<p>Given a, b, c, target t = nums[a] + nums[b] + nums[c], we check the hashtable and use binary search to find how many times it occurred after index c.</p>



<p>Time complexity: O(n<sup>3</sup>/6*logn)<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 countQuadruplets(vector&lt;int&gt;&amp; nums) {
    constexpr int kMax = 100;
    const int n = nums.size();
    int ans = 0;
    vector&lt;vector&lt;int&gt;&gt; m(kMax + 1);
    for (int i = 0; i &lt; n; ++i)
      m[nums[i]].push_back(i);
    for (int a = 0; a &lt; n; ++a)
      for (int b = a + 1; b &lt; n; ++b)
        for (int c = b + 1; c &lt; n; ++c) {
          const int t = nums[a] + nums[b] + nums[c];
          if (t &gt; kMax) continue;
          ans += end(m[t]) - lower_bound(begin(m[t]), end(m[t]), c + 1);
        }
    return ans;
  }
};</pre>
</div></div>



<p></p>



<p></p>



<h2><strong>Solution 3: Dynamic frequency table (29ms)</strong></h2>



<p>Similar to <a rel="noreferrer noopener" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1-two-sum/" data-type="post" data-id="903" target="_blank">花花酱 LeetCode 1. Two Sum</a>, we dynamically add elements (from right to left) into the hashtable.</p>



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



<p></p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int countQuadruplets(vector&lt;int&gt;&amp; nums) {
    constexpr int kMax = 100;
    const int n = nums.size();
    int ans = 0;
    vector&lt;int&gt; m(kMax + 1);    
    // for every c we had seen, we can use it as target (nums[d]).
    for (int c = n - 1; c &gt;= 0; ++m[nums[c--]])
      for (int a = 0; a &lt; c; ++a)
        for (int b = a + 1; b &lt; c; ++b) {
          const int t = nums[a] + nums[b] + nums[c];
          if (t &gt; kMax) continue;
          ans += m[t];
        }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1995-count-special-quadruplets/">花花酱 LeetCode 1995. Count Special Quadruplets</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-1995-count-special-quadruplets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1300. Sum of Mutated Array Closest to Target</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1300-sum-of-mutated-array-closest-to-target/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1300-sum-of-mutated-array-closest-to-target/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 24 Dec 2021 08:15:09 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9214</guid>

					<description><![CDATA[<p>Given an integer array&#160;arr&#160;and a target value&#160;target, return the integer&#160;value&#160;such that when we change all the integers larger than&#160;value&#160;in the given array to be equal&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1300-sum-of-mutated-array-closest-to-target/">花花酱 LeetCode 1300. Sum of Mutated Array Closest to Target</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given an integer array&nbsp;<code>arr</code>&nbsp;and a target value&nbsp;<code>target</code>, return the integer&nbsp;<code>value</code>&nbsp;such that when we change all the integers larger than&nbsp;<code>value</code>&nbsp;in the given array to be equal to&nbsp;<code>value</code>, the sum of the array gets as close as possible (in absolute difference) to&nbsp;<code>target</code>.</p>



<p>In case of a tie, return the minimum such integer.</p>



<p>Notice that the answer is not neccesarilly a number from&nbsp;<code>arr</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,9,3], target = 10
<strong>Output:</strong> 3
<strong>Explanation:</strong> When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,3,5], target = 10
<strong>Output:</strong> 5
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [60864,25176,27249,21296,20204], target = 56803
<strong>Output:</strong> 11361
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= arr[i], target &lt;= 10<sup>5</sup></code></li></ul>



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



<p>Find the smallest number x s.t. sum of the mutated array is >= target. Answer must be either x or x &#8211; 1.</p>



<p>Note, the search range should be [0, max(arr))</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua]
class Solution {
public:
  int findBestValue(vector&lt;int&gt;&amp; arr, int target) {
    int l = 0;
    int r = *max_element(begin(arr), end(arr));
    int ans = 0;
    auto sum = [&amp;](int v) {
      int ans = 0;
      for (int x : arr)
        ans += min(x, v);
      return ans;
    };
    while (l &lt; r) {
      int m = l + (r - l) / 2;            
      if (sum(m) &gt;= target)
        r = m;
      else
        l = m + 1;
    }
    return abs(sum(l) - target) &lt; abs(sum(l - 1) - target) ? l : l - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1300-sum-of-mutated-array-closest-to-target/">花花酱 LeetCode 1300. Sum of Mutated Array Closest to Target</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1300-sum-of-mutated-array-closest-to-target/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2111. Minimum Operations to Make the Array K-Increasing</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2111-minimum-operations-to-make-the-array-k-increasing/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2111-minimum-operations-to-make-the-array-k-increasing/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 22 Dec 2021 19:55:14 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[LIS]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9193</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;array&#160;arr&#160;consisting of&#160;n&#160;positive integers, and a positive integer&#160;k. The array&#160;arr&#160;is called&#160;K-increasing&#160;if&#160;arr[i-k] &#60;= arr[i]&#160;holds for every index&#160;i, where&#160;k &#60;= i &#60;= n-1. For example,&#160;arr&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2111-minimum-operations-to-make-the-array-k-increasing/">花花酱 LeetCode 2111. Minimum Operations to Make the Array K-Increasing</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array&nbsp;<code>arr</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;positive integers, and a positive integer&nbsp;<code>k</code>.</p>



<p>The array&nbsp;<code>arr</code>&nbsp;is called&nbsp;<strong>K-increasing</strong>&nbsp;if&nbsp;<code>arr[i-k] &lt;= arr[i]</code>&nbsp;holds for every index&nbsp;<code>i</code>, where&nbsp;<code>k &lt;= i &lt;= n-1</code>.</p>



<ul><li>For example,&nbsp;<code>arr = [4, 1, 5, 2, 6, 2]</code>&nbsp;is K-increasing for&nbsp;<code>k = 2</code>&nbsp;because:<ul><li><code>arr[0] &lt;= arr[2] (4 &lt;= 5)</code></li><li><code>arr[1] &lt;= arr[3] (1 &lt;= 2)</code></li><li><code>arr[2] &lt;= arr[4] (5 &lt;= 6)</code></li><li><code>arr[3] &lt;= arr[5] (2 &lt;= 2)</code></li></ul></li><li>However, the same&nbsp;<code>arr</code>&nbsp;is not K-increasing for&nbsp;<code>k = 1</code>&nbsp;(because&nbsp;<code>arr[0] &gt; arr[1]</code>) or&nbsp;<code>k = 3</code>&nbsp;(because&nbsp;<code>arr[0] &gt; arr[3]</code>).</li></ul>



<p>In one&nbsp;<strong>operation</strong>, you can choose an index&nbsp;<code>i</code>&nbsp;and&nbsp;<strong>change</strong>&nbsp;<code>arr[i]</code>&nbsp;into&nbsp;<strong>any</strong>&nbsp;positive integer.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum number of operations</strong>&nbsp;required to make the array K-increasing for the given&nbsp;</em><code>k</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [5,4,3,2,1], k = 1
<strong>Output:</strong> 4
<strong>Explanation:
</strong>For k = 1, the resultant array has to be non-decreasing.
Some of the K-increasing arrays that can be formed are [5,<strong>6</strong>,<strong>7</strong>,<strong>8</strong>,<strong>9</strong>], [<strong>1</strong>,<strong>1</strong>,<strong>1</strong>,<strong>1</strong>,1], [<strong>2</strong>,<strong>2</strong>,3,<strong>4</strong>,<strong>4</strong>]. All of them require 4 operations.
It is suboptimal to change the array to, for example, [<strong>6</strong>,<strong>7</strong>,<strong>8</strong>,<strong>9</strong>,<strong>10</strong>] because it would take 5 operations.
It can be shown that we cannot make the array K-increasing in less than 4 operations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,1,5,2,6,2], k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong>
This is the same example as the one in the problem description.
Here, for every index i where 2 &lt;= i &lt;= 5, arr[i-2] &lt;=arr[i].
Since the given array is already K-increasing, we do not need to perform any operations.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,1,5,2,6,2], k = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong>
Indices 3 and 5 are the only ones not satisfying arr[i-3] &lt;= arr[i] for 3 &lt;= i &lt;= 5.
One of the ways we can make the array K-increasing is by changing arr[3] to 4 and arr[5] to 5.
The array will now be [4,1,5,<strong>4</strong>,6,<strong>5</strong>].
Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.
</pre>



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



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



<h2><strong>Solution: Longest increasing subsequence</strong></h2>



<p>if k = 1, <meta charset="utf-8">we need to modify the following arrays<br>1. [a[0], a[1], a[2], &#8230;]<br>if k = 2, <meta charset="utf-8">we need to modify the following arrays<br>1. <meta charset="utf-8">[a[0], a[2], a[4], &#8230;]<br>2. [a[1], a[3], a[5], &#8230;]<br>if k = 3, we need to modify the following arrays<br><meta charset="utf-8">1. <meta charset="utf-8">[a[0], a[3], a[6], &#8230;]<br>2. [a[1], a[4], a[7], &#8230;]<br>3. <meta charset="utf-8">[a[2], a[5], a[8], &#8230;]<br>&#8230;</p>



<p>These arrays are independent of each other, we just need to find LIS of it, # ops = len(arr) &#8211; LIS(arr).<br>Ans = sum(len(arr<sub>i</sub>) &#8211; LIS(arr<sub>i</sub>))  1 &lt;= i &lt;= k</p>



<p>Reference: <a href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-300-longest-increasing-subsequence/" data-type="post" data-id="206">花花酱 LeetCode 300. Longest Increasing Subsequence</a></p>



<p>Time complexity: O(k * (n/k)* log(n/k)) = O(n * log(n/k))<br>Space complexity: O(n/k)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int kIncreasing(vector&lt;int&gt;&amp; arr, int k) {
    auto LIS = [](const vector&lt;int&gt;&amp; nums) {
      vector&lt;int&gt; lis;
      for (int x : nums)
        if (lis.empty() || lis.back() &lt;= x)
          lis.push_back(x);
        else
          *upper_bound(begin(lis), end(lis), x) = x;
      return lis.size();
    };
    const int n = arr.size();
    int ans = 0;
    for (int i = 0; i &lt; k; ++i) {
      vector&lt;int&gt; cur;
      for (int j = i; j &lt; n; j += k)
        cur.push_back(arr[j]);
      ans += cur.size() - LIS(cur);
    }
    return ans;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def kIncreasing(self, arr: List[int], k: int) -&gt; int:
    def LIS(arr: List[int]) -&gt; int:
      lis = []
      for x in arr:
        if not lis or lis[-1] &lt;= x:
          lis.append(x)
        else:
          lis[bisect_right(lis, x)] = x
      return len(lis)
    
    return sum(len(arr[i::k]) - LIS(arr[i::k]) for i in range(k))</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2111-minimum-operations-to-make-the-array-k-increasing/">花花酱 LeetCode 2111. Minimum Operations to Make the Array K-Increasing</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2111-minimum-operations-to-make-the-array-k-increasing/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 81. Search in Rotated Sorted Array II</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-81-search-in-rotated-sorted-array-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-81-search-in-rotated-sorted-array-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 29 Nov 2021 08:47:01 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[rotated]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8937</guid>

					<description><![CDATA[<p>There is an integer array&#160;nums&#160;sorted in non-decreasing order (not necessarily with&#160;distinct&#160;values). Before being passed to your function,&#160;nums&#160;is&#160;rotated&#160;at an unknown pivot index&#160;k&#160;(0 &#60;= k &#60; nums.length)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-81-search-in-rotated-sorted-array-ii/">花花酱 LeetCode 81. Search in Rotated Sorted Array II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>There is an integer array&nbsp;<code>nums</code>&nbsp;sorted in non-decreasing order (not necessarily with&nbsp;<strong>distinct</strong>&nbsp;values).</p>



<p>Before being passed to your function,&nbsp;<code>nums</code>&nbsp;is&nbsp;<strong>rotated</strong>&nbsp;at an unknown pivot index&nbsp;<code>k</code>&nbsp;(<code>0 &lt;= k &lt; nums.length</code>) such that the resulting array is&nbsp;<code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code>&nbsp;(<strong>0-indexed</strong>). For example,&nbsp;<code>[0,1,2,4,4,4,5,6,6,7]</code>&nbsp;might be rotated at pivot index&nbsp;<code>5</code>&nbsp;and become&nbsp;<code>[4,5,6,6,7,0,1,2,4,4]</code>.</p>



<p>Given the array&nbsp;<code>nums</code>&nbsp;<strong>after</strong>&nbsp;the rotation and an integer&nbsp;<code>target</code>, return&nbsp;<code>true</code><em>&nbsp;if&nbsp;</em><code>target</code><em>&nbsp;is in&nbsp;</em><code>nums</code><em>, or&nbsp;</em><code>false</code><em>&nbsp;if it is not in&nbsp;</em><code>nums</code><em>.</em></p>



<p>You must decrease the overall operation steps as much as possible.</p>



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



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



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



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



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



<ul><li><code>1 &lt;= nums.length &lt;= 5000</code></li><li><code>-10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>4</sup></code></li><li><code>nums</code>&nbsp;is guaranteed to be rotated at some pivot.</li><li><code>-10<sup>4</sup>&nbsp;&lt;= target &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Binary search or divide and conquer</strong></h2>



<p>If current range is ordered, use binary search, Otherwise, divide and conquer.</p>



<p>Time complexity: O(logn) best, O(n) worst<br>Space complexity: O(logn)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  bool search(vector&lt;int&gt;&amp; A, int target) {
    return search(A, 0, A.size() - 1, target);
  }
private:
  bool search(vector&lt;int&gt;&amp; A, int l, int r, int target) {
    if (l &gt; r) return 0;
    if (l == r) return target == A[l];

    int mid = l + (r - l) / 2;

    if (A[l] &lt; A[mid] &amp;&amp; A[mid] &lt; A[r])
      return (target &lt;= A[mid]) ? search(A, l, mid, target) : search(A, mid + 1, r, target);
    else
      return search(A, l, mid, target) || search(A, mid + 1, r, target);
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-81-search-in-rotated-sorted-array-ii/">花花酱 LeetCode 81. Search in Rotated Sorted Array II</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-81-search-in-rotated-sorted-array-ii/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 69. Sqrt(x)</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-69-sqrtx-2/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-69-sqrtx-2/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Nov 2021 05:19:34 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8808</guid>

					<description><![CDATA[<p>Given a non-negative integer&#160;x,&#160;compute and return&#160;the square root of&#160;x. Since the return type&#160;is an integer, the decimal digits are&#160;truncated, and only&#160;the integer part&#160;of the result&#160;is&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-69-sqrtx-2/">花花酱 LeetCode 69. Sqrt(x)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given a non-negative integer&nbsp;<code>x</code>,&nbsp;compute and return&nbsp;<em>the square root of</em>&nbsp;<code>x</code>.</p>



<p>Since the return type&nbsp;is an integer, the decimal digits are&nbsp;<strong>truncated</strong>, and only&nbsp;<strong>the integer part</strong>&nbsp;of the result&nbsp;is returned.</p>



<p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in exponent function or operator, such as&nbsp;<code>pow(x, 0.5)</code>&nbsp;or&nbsp;<code>x ** 0.5</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> x = 4
<strong>Output:</strong> 2
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> x = 8
<strong>Output:</strong> 2
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.</pre>



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



<ul><li><code>0 &lt;= x &lt;= 2<sup>31</sup>&nbsp;- 1</code></li></ul>



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



<p>Find the smallest l such that l * l > x, sqrt(x) = l &#8211; 1.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int mySqrt(int x) {      
    unsigned l = 1;
    unsigned r = 1u + x;
    while (l &lt; r) {
      unsigned m = l + (r - l) / 2;
      if (m &gt; x / m) { 
        r = m;
      } else {
        l = m + 1;
      }
    }
    return l - 1;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-69-sqrtx-2/">花花酱 LeetCode 69. Sqrt(x)</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-69-sqrtx-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 34. Find First and Last Position of Element in Sorted Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-2/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-2/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Nov 2021 02:02:50 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8797</guid>

					<description><![CDATA[<p>Given an array of integers&#160;nums&#160;sorted in non-decreasing order, find the starting and ending position of a given&#160;target&#160;value. If&#160;target&#160;is not found in the array, return&#160;[-1, -1].&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-2/">花花酱 LeetCode 34. Find First and Last Position of Element in Sorted 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>Given an array of integers&nbsp;<code>nums</code>&nbsp;sorted in non-decreasing order, find the starting and ending position of a given&nbsp;<code>target</code>&nbsp;value.</p>



<p>If&nbsp;<code>target</code>&nbsp;is not found in the array, return&nbsp;<code>[-1, -1]</code>.</p>



<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code>&nbsp;runtime complexity.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8
<strong>Output:</strong> [3,4]
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6
<strong>Output:</strong> [-1,-1]
</pre>



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



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



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



<ul><li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li><li><code>nums</code>&nbsp;is a non-decreasing array.</li><li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li></ul>



<p><strong>Solution: Binary Search</strong></p>



<p>Use lower_bound to find first<br>Use upper_bound to find last + 1</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; searchRange(vector&lt;int&gt;&amp; nums, int target) {
    auto it = lower_bound(begin(nums), end(nums), target);
    int l = (it == end(nums) || *it != target) ? -1 : it - begin(nums);
    auto it2 = upper_bound(begin(nums), end(nums), target);
    int r = (it2 == begin(nums) || *prev(it2) != target) ? -1 : prev(it2) - begin(nums);
    return {l, r};
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-2/">花花酱 LeetCode 34. Find First and Last Position of Element in Sorted 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/algorithms/binary-search/leetcode-34-find-first-and-last-position-of-element-in-sorted-array-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 33. Search in Rotated Sorted Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-33-search-in-rotated-sorted-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-33-search-in-rotated-sorted-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 27 Nov 2021 01:51:32 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[rotated]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8793</guid>

					<description><![CDATA[<p>There is an integer array&#160;nums&#160;sorted in ascending order (with&#160;distinct&#160;values). Prior to being passed to your function,&#160;nums&#160;is&#160;possibly rotated&#160;at an unknown pivot index&#160;k&#160;(1 &#60;= k &#60; nums.length)&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-33-search-in-rotated-sorted-array/">花花酱 LeetCode 33. Search in Rotated Sorted 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>There is an integer array&nbsp;<code>nums</code>&nbsp;sorted in ascending order (with&nbsp;<strong>distinct</strong>&nbsp;values).</p>



<p>Prior to being passed to your function,&nbsp;<code>nums</code>&nbsp;is&nbsp;<strong>possibly rotated</strong>&nbsp;at an unknown pivot index&nbsp;<code>k</code>&nbsp;(<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is&nbsp;<code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code>&nbsp;(<strong>0-indexed</strong>). For example,&nbsp;<code>[0,1,2,4,5,6,7]</code>&nbsp;might be rotated at pivot index&nbsp;<code>3</code>&nbsp;and become&nbsp;<code>[4,5,6,7,0,1,2]</code>.</p>



<p>Given the array&nbsp;<code>nums</code>&nbsp;<strong>after</strong>&nbsp;the possible rotation and an integer&nbsp;<code>target</code>, return&nbsp;<em>the index of&nbsp;</em><code>target</code><em>&nbsp;if it is in&nbsp;</em><code>nums</code><em>, or&nbsp;</em><code>-1</code><em>&nbsp;if it is not in&nbsp;</em><code>nums</code>.</p>



<p>You must write an algorithm with&nbsp;<code>O(log n)</code>&nbsp;runtime complexity.</p>



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



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



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



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



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



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



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



<ul><li><code>1 &lt;= nums.length &lt;= 5000</code></li><li><code>-10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>4</sup></code></li><li>All values of&nbsp;<code>nums</code>&nbsp;are&nbsp;<strong>unique</strong>.</li><li><code>nums</code>&nbsp;is an ascending array that is possibly rotated.</li><li><code>-10<sup>4</sup>&nbsp;&lt;= target &lt;= 10<sup>4</sup></code></li></ul>



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



<p>If the current range [l, r] is ordered, reduce to normal binary search. Otherwise, determine the range to search next by comparing target and nums[0].</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int search(vector&lt;int&gt;&amp; nums, int target) {
    int l = 0;
    int r = nums.size();
    while (l &lt; r) {
      int m = l + (r - l) / 2;
      int x = (nums[m] &lt; nums[0]) == (target &lt; nums[0])
              ? nums[m]
              : target &lt; nums[0] ? INT_MIN : INT_MAX;
      if (x &lt; target)
        l = m + 1;
      else if (x &gt; target)
        r = m;
      else
        return m;
    }
    return -1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-33-search-in-rotated-sorted-array/">花花酱 LeetCode 33. Search in Rotated Sorted 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/algorithms/binary-search/leetcode-33-search-in-rotated-sorted-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2080. Range Frequency Queries</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2080-range-frequency-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2080-range-frequency-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Nov 2021 08:18:34 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8753</guid>

					<description><![CDATA[<p>Design a data structure to find the&#160;frequency&#160;of a given value in a given subarray. The&#160;frequency&#160;of a value in a subarray is the number of occurrences&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2080-range-frequency-queries/">花花酱 LeetCode 2080. Range Frequency Queries</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>Design a data structure to find the&nbsp;<strong>frequency</strong>&nbsp;of a given value in a given subarray.</p>



<p>The&nbsp;<strong>frequency</strong>&nbsp;of a value in a subarray is the number of occurrences of that value in the subarray.</p>



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



<ul><li><code>RangeFreqQuery(int[] arr)</code>&nbsp;Constructs an instance of the class with the given&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>arr</code>.</li><li><code>int query(int left, int right, int value)</code>&nbsp;Returns the&nbsp;<strong>frequency</strong>&nbsp;of&nbsp;<code>value</code>&nbsp;in the subarray&nbsp;<code>arr[left...right]</code>.</li></ul>



<p>A&nbsp;<strong>subarray</strong>&nbsp;is a contiguous sequence of elements within an array.&nbsp;<code>arr[left...right]</code>&nbsp;denotes the subarray that contains the elements of&nbsp;<code>nums</code>&nbsp;between indices&nbsp;<code>left</code>&nbsp;and&nbsp;<code>right</code>&nbsp;(<strong>inclusive</strong>).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input</strong>
["RangeFreqQuery", "query", "query"]
[[[12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]], [1, 2, 4], [0, 11, 33]]
<strong>Output</strong>
</pre>


<p>[null, 1, 2]</p>



<p><strong>Explanation</strong> RangeFreqQuery rangeFreqQuery = new RangeFreqQuery([12, 33, 4, 56, 22, 2, 34, 33, 22, 12, 34, 56]); rangeFreqQuery.query(1, 2, 4); // return 1. The value 4 occurs 1 time in the subarray [33, 4] rangeFreqQuery.query(0, 11, 33); // return 2. The value 33 occurs 2 times in the whole array.</p>



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



<ul><li><code>1 &lt;= arr.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arr[i], value &lt;= 10<sup>4</sup></code></li><li><code>0 &lt;= left &lt;= right &lt; arr.length</code></li><li>At most&nbsp;<code>10<sup>5</sup></code>&nbsp;calls will be made to&nbsp;<code>query</code></li></ul>



<p>Solution: Hashtable + Binary Search</p>



<p>Time complexity: Init: O(max(arr) + n), query: O(logn)<br>Space complexity: O(max(arr) + n)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class RangeFreqQuery {
public:
  RangeFreqQuery(vector&lt;int&gt;&amp; arr) : s_(10001) {
    for (int i = 0; i &lt; arr.size(); ++i)
      s_[arr[i]].push_back(i);
  }

  int query(int left, int right, int value) {
    const auto&amp; m = s_[value];
    if (m.empty()) return 0;
    auto r = prev(upper_bound(begin(m), end(m), right));
    auto l = lower_bound(begin(m), end(m), left);    
    return r - l + 1;
  }
private:
  vector&lt;vector&lt;int&gt;&gt; s_;
};
/**
 * Your RangeFreqQuery object will be instantiated and called as such:
 * RangeFreqQuery* obj = new RangeFreqQuery(arr);
 * int param_1 = obj-&gt;query(left,right,value);
 */</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2080-range-frequency-queries/">花花酱 LeetCode 2080. Range Frequency Queries</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2080-range-frequency-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2071. Maximum Number of Tasks You Can Assign</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2071-maximum-number-of-tasks-you-can-assign/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2071-maximum-number-of-tasks-you-can-assign/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 15 Nov 2021 04:45:28 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[Greedy]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[hard]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8702</guid>

					<description><![CDATA[<p>You have&#160;n&#160;tasks and&#160;m&#160;workers. Each task has a strength requirement stored in a&#160;0-indexed&#160;integer array&#160;tasks, with the&#160;ith&#160;task requiring&#160;tasks[i]&#160;strength to complete. The strength of each worker is stored&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2071-maximum-number-of-tasks-you-can-assign/">花花酱 LeetCode 2071. Maximum Number of Tasks You Can Assign</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 have&nbsp;<code>n</code>&nbsp;tasks and&nbsp;<code>m</code>&nbsp;workers. Each task has a strength requirement stored in a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>tasks</code>, with the&nbsp;<code>i<sup>th</sup></code>&nbsp;task requiring&nbsp;<code>tasks[i]</code>&nbsp;strength to complete. The strength of each worker is stored in a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>workers</code>, with the&nbsp;<code>j<sup>th</sup></code>&nbsp;worker having&nbsp;<code>workers[j]</code>&nbsp;strength. Each worker can only be assigned to a&nbsp;<strong>single</strong>&nbsp;task and must have a strength&nbsp;<strong>greater than or equal</strong>&nbsp;to the task&#8217;s strength requirement (i.e.,&nbsp;<code>workers[j] &gt;= tasks[i]</code>).</p>



<p>Additionally, you have&nbsp;<code>pills</code>&nbsp;magical pills that will&nbsp;<strong>increase a worker&#8217;s strength</strong>&nbsp;by&nbsp;<code>strength</code>. You can decide which workers receive the magical pills, however, you may only give each worker&nbsp;<strong>at most one</strong>&nbsp;magical pill.</p>



<p>Given the&nbsp;<strong>0-indexed&nbsp;</strong>integer arrays&nbsp;<code>tasks</code>&nbsp;and&nbsp;<code>workers</code>&nbsp;and the integers&nbsp;<code>pills</code>&nbsp;and&nbsp;<code>strength</code>, return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of tasks that can be completed.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tasks = [<strong>3</strong>,<strong>2</strong>,<strong>1</strong>], workers = [<strong>0</strong>,<strong>3</strong>,<strong>3</strong>], pills = 1, strength = 1
<strong>Output:</strong> 3
<strong>Explanation:</strong>
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 2 (0 + 1 &gt;= 1)
- Assign worker 1 to task 1 (3 &gt;= 2)
- Assign worker 2 to task 0 (3 &gt;= 3)
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tasks = [<strong>5</strong>,4], workers = [<strong>0</strong>,0,0], pills = 1, strength = 5
<strong>Output:</strong> 1
<strong>Explanation:</strong>
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 0.
- Assign worker 0 to task 0 (0 + 5 &gt;= 5)
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tasks = [<strong>10</strong>,<strong>15</strong>,30], workers = [<strong>0</strong>,<strong>10</strong>,10,10,10], pills = 3, strength = 10
<strong>Output:</strong> 2
<strong>Explanation:</strong>
We can assign the magical pills and tasks as follows:
- Give the magical pill to worker 0 and worker 1.
- Assign worker 0 to task 0 (0 + 10 &gt;= 10)
- Assign worker 1 to task 1 (10 + 10 &gt;= 15)
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> tasks = [<strong>5</strong>,9,<strong>8</strong>,<strong>5</strong>,9], workers = [1,<strong><u>6</u></strong>,<strong>4</strong>,2,<strong>6</strong>], pills = 1, strength = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong>
We can assign the magical pill and tasks as follows:
- Give the magical pill to worker 2.
- Assign worker 1 to task 0 (6 &gt;= 5)
- Assign worker 2 to task 2 (4 + 5 &gt;= 8)
- Assign worker 4 to task 3 (6 &gt;= 5)
</pre>



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



<ul><li><code>n == tasks.length</code></li><li><code>m == workers.length</code></li><li><code>1 &lt;= n, m &lt;= 5 * 10<sup>4</sup></code></li><li><code>0 &lt;= pills &lt;= m</code></li><li><code>0 &lt;= tasks[i], workers[j], strength &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Greedy + Binary Search in Binary Search.</strong></h2>



<p>Find the smallest k, s.t. we are <strong>NOT</strong> able to assign. Then answer is k- 1.</p>



<p>The key is to <strong>verify</strong> whether we can assign k tasks or not.</p>



<p>Greedy: We want k smallest tasks and k strongest workers.</p>



<p>Start with the hardest tasks among (smallest) k:<br>1. assign task[i] to the weakest worker without a pill (if he can handle the hardest work so far, then the stronger workers can handle any simpler tasks left)<br>2. If 1) is not possible, we find a weakest worker + pill that can handle task[i] (otherwise we are wasting workers)<br>3. If 2) is not possible, impossible to finish k tasks.</p>



<p>Let k = min(n, m)<br>Time complexity: O((logk)<sup>2</sup> * k)<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
class Solution {
public:
  int maxTaskAssign(vector&lt;int&gt;&amp; tasks, vector&lt;int&gt;&amp; workers, int pills, int strength) {
    const int n = tasks.size();    
    sort(begin(tasks), end(tasks));    
    sort(begin(workers), end(workers)); 
    auto check = [&amp;](int k) {      
      multiset&lt;int&gt; ws(rbegin(workers), rbegin(workers) + k);
      for (int i = k - 1, p = 0; i &gt;= 0; --i) {
        auto it = ws.lower_bound(tasks[i]);
        if (it != end(ws)) {
          ws.erase(it);
        } else if ((it = ws.lower_bound(tasks[i] - strength)) != end(ws)) {
          if (++p &gt; pills) return false;
          ws.erase(it);
        } else {
          return false;
        }
      }
      return true;
    };
    int l = 0;
    int r = min(tasks.size(), workers.size()) + 1;
    while (l &lt; r) {
      int m = l + (r - l) / 2;
      if (!check(m)) {
        r = m;
      } else {
        l = m + 1;
      }
    }
    return l - 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2071-maximum-number-of-tasks-you-can-assign/">花花酱 LeetCode 2071. Maximum Number of Tasks You Can Assign</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-2071-maximum-number-of-tasks-you-can-assign/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
