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

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>greedy &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 646. Maximum Length of Pair Chain</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-646-maximum-length-of-pair-chain/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-646-maximum-length-of-pair-chain/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 10 Apr 2025 05:25:42 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Greedy]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[proof]]></category>
		<category><![CDATA[subset]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10301</guid>

					<description><![CDATA[这题我选DP，因为不需要证明，直接干就行了。 方法1: DP 首先还是需要对pairs的right进行排序。一方面是为了方便chaining，另一方面是可以去重。 然后定义 dp[i] := 以pairs[i]作为结尾，最长的序列的长度。 状态转移：dp[i] = max(dp[j] + 1) where pairs[i].left > pairs[j].right and 0 &#60; j &#60; i. 解释：对于pairs[i]，找一个最优的pairs[j]，满足pairs[i].left >&#8230;]]></description>
										<content:encoded><![CDATA[
<p>这题我选DP，因为不需要证明，直接干就行了。</p>



<p>方法1: DP</p>



<p>首先还是需要对pairs的right进行排序。一方面是为了方便chaining，另一方面是可以去重。</p>



<p>然后定义 dp[i] := 以pairs[i]作为结尾，最长的序列的长度。<br><br>状态转移：dp[i] = max(dp[j] + 1) where pairs[i].left > pairs[j].right and 0 &lt; j &lt; i.</p>



<p>解释：对于pairs[i]，找一个最优的pairs[j]，满足pairs[i].left > pairs[j].right，这样我就可以把pairs[i]追加到以pairs[j]结尾的最长序列后面了，长度+1。</p>



<p>边检条件：dp[0:n] = 1，每个pair以自己作为序列的最后元素，长度为1。</p>



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



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int findLongestChain(vector&lt;vector&lt;int&gt;&gt;&amp; pairs) {
    sort(begin(pairs), end(pairs), [](const auto&amp; p1, const auto&amp; p2){
      return p1[1] &lt; p2[1];
    });

    const int n = pairs.size();

    vector&lt;int&gt; dp(n, 1);
    for (int i = 0; i &lt; n; ++i)
      for (int j = 0; j &lt; i; ++j)
        if (pairs[i][0] &gt; pairs[j][1])
          dp[i] = max(dp[i], dp[j] + 1);

    return *max_element(begin(dp), end(dp));
  }
};</pre>



<p>方法2: 贪心</p>



<p>和DP一样，对数据进行排序。</p>



<p>每当我看到 cur.left > prev.right，那么就直接把cur接在prev后面。我们需要证明这么做是最优的，而不是跳过它选后面的元素。<br><br>Case 0: cur已经是最后一个元素了，跳过就不是最优解了。<br><br>假设cur后面有next, 因为已经排序过了，我们可以得知 next.right >= cur.right。<br><br>Case 1: next.right == cur.right。这时候选cur和选next对后面的决策来说是一样的，但由于Case 0的存在，我必须选cur。<br><br>Case 2: next.right > cur.right。不管left的情况怎么样，由于right更小，这时候选择cur一定是优于next。</p>



<p>综上所述，看到有元素可以连接起来就贪心的选它就对了。</p>



<p>时间复杂度：O(nlogn)<br>空间复杂度：O(1)</p>



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int findLongestChain(vector&lt;vector&lt;int&gt;&gt;&amp; pairs) {
    sort(begin(pairs), end(pairs), [](const auto&amp; p1, const auto&amp; p2){
      return p1[1] &lt; p2[1];
    });

    int right = INT_MIN;
    int ans = 0;
    for (const auto&amp; p : pairs)
      if (p[0] &gt; right) {
        right = p[1];
        ++ans;
      }
    return ans;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-646-maximum-length-of-pair-chain/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2829. Determine the Minimum Sum of a k-avoiding Array</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Aug 2023 16:40:51 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10085</guid>

					<description><![CDATA[You are given two integers,&#160;n&#160;and&#160;k. An array of&#160;distinct&#160;positive integers is called a&#160;k-avoiding&#160;array if there does not exist any pair of distinct elements that sum to&#160;k.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two integers,&nbsp;<code>n</code>&nbsp;and&nbsp;<code>k</code>.</p>



<p>An array of&nbsp;<strong>distinct</strong>&nbsp;positive integers is called a&nbsp;<strong>k-avoiding</strong>&nbsp;array if there does not exist any pair of distinct elements that sum to&nbsp;<code>k</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;possible sum of a k-avoiding array of length&nbsp;</em><code>n</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 5, k = 4
<strong>Output:</strong> 18
<strong>Explanation:</strong> Consider the k-avoiding array [1,2,4,5,6], which has a sum of 18.
It can be proven that there is no k-avoiding array with a sum less than 18.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> n = 2, k = 6
<strong>Output:</strong> 3
<strong>Explanation:</strong> We can construct the array [1,2], which has a sum of 3.
It can be proven that there is no k-avoiding array with a sum less than 3.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= n, k &lt;= 50</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Greedy + HashTable</strong></h2>



<p>Always choose the smallest possible number starting from 1.</p>



<p>Add all chosen numbers into a hashtable. For a new candidate i, check whether k &#8211; i is already in the hashtable.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minimumSum(int n, int k) {    
    int sum = 0;
    unordered_set&lt;int&gt; s;
    for (int i = 1; s.size() != n; ++i) {
      if (s.count(k - i)) continue;
      sum += i;
      s.insert(i);
    }
    return sum;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2829-determine-the-minimum-sum-of-a-k-avoiding-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2769. Find the Maximum Achievable Number</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2769-find-the-maximum-achievable-number/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2769-find-the-maximum-achievable-number/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 12 Jul 2023 01:12:33 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10057</guid>

					<description><![CDATA[You are given two integers,&#160;num&#160;and&#160;t. An integer&#160;x&#160;is called&#160;achievable&#160;if it can become equal to&#160;num&#160;after applying the following operation no more than&#160;t&#160;times: Increase or decrease&#160;x&#160;by&#160;1, and simultaneously&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two integers,&nbsp;<code>num</code>&nbsp;and&nbsp;<code>t</code>.</p>



<p>An integer&nbsp;<code>x</code>&nbsp;is called&nbsp;<strong>achievable</strong>&nbsp;if it can become equal to&nbsp;<code>num</code>&nbsp;after applying the following operation no more than&nbsp;<code>t</code>&nbsp;times:</p>



<ul class="wp-block-list"><li>Increase or decrease&nbsp;<code>x</code>&nbsp;by&nbsp;<code>1</code>, and simultaneously increase or decrease&nbsp;<code>num</code>&nbsp;by&nbsp;<code>1</code>.</li></ul>



<p>Return&nbsp;<em>the maximum possible achievable number</em>. It can be proven that there exists at least one achievable number.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 4, t = 1
<strong>Output:</strong> 6
<strong>Explanation:</strong> The maximum achievable number is x = 6; it can become equal to num after performing this operation:
1- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5. 
It can be proven that there is no achievable number larger than 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> num = 3, t = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> The maximum achievable number is x = 7; after performing these operations, x will equal num: 
1- Decrease x by 1, and increase num by 1. Now, x = 6 and num = 4.
2- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5.
It can be proven that there is no achievable number larger than 7.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= num, t&nbsp;&lt;= 50</code></li></ul>



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



<p>Always decrease x and always increase num, the max achievable number  x = num + t * 2</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int theMaximumAchievableX(int num, int t) {
    return num + t * 2;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2769-find-the-maximum-achievable-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2656. Maximum Sum With Exactly K Elements</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2656-maximum-sum-with-exactly-k-elements/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2656-maximum-sum-with-exactly-k-elements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Apr 2023 14:58:44 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[math]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10022</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;and an integer&#160;k. Your task is to perform the following operation&#160;exactly&#160;k&#160;times in order to maximize your score: Select an element&#160;m&#160;from&#160;nums. Remove&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. Your task is to perform the following operation&nbsp;<strong>exactly</strong>&nbsp;<code>k</code>&nbsp;times in order to maximize your score:</p>



<ol class="wp-block-list"><li>Select an element&nbsp;<code>m</code>&nbsp;from&nbsp;<code>nums</code>.</li><li>Remove the selected element&nbsp;<code>m</code>&nbsp;from the array.</li><li>Add a new element with a value of&nbsp;<code>m + 1</code>&nbsp;to the array.</li><li>Increase your score by&nbsp;<code>m</code>.</li></ol>



<p>Return&nbsp;<em>the maximum score you can achieve after performing the operation exactly</em>&nbsp;<code>k</code>&nbsp;<em>times.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4,5], k = 3
<strong>Output:</strong> 18
<strong>Explanation:</strong> We need to choose exactly 3 elements from nums to maximize the sum.
For the first iteration, we choose 5. Then sum is 5 and nums = [1,2,3,4,6]
For the second iteration, we choose 6. Then sum is 5 + 6 and nums = [1,2,3,4,7]
For the third iteration, we choose 7. Then sum is 5 + 6 + 7 = 18 and nums = [1,2,3,4,8]
So, we will return 18.
It can be proven, that 18 is the maximum answer that we can achieve.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,5,5], k = 2
<strong>Output:</strong> 11
<strong>Explanation:</strong> We need to choose exactly 2 elements from nums to maximize the sum.
For the first iteration, we choose 5. Then sum is 5 and nums = [5,5,6]
For the second iteration, we choose 6. Then sum is 5 + 6 = 11 and nums = [5,5,7]
So, we will return 11.
It can be proven, that 11 is the maximum answer that we can achieve.
</pre>



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



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



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



<p>Always to chose the largest element from the array.</p>



<p>We can find the largest element of the array m, then the total score will be<br>m + (m + 1) + (m + 2) + &#8230; + (m + k &#8211; 1),<br>We can use summation formula of arithmetic sequence to compute that in O(1)<br>ans = (m + (m + k &#8211; 1)) * k / 2</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximizeSum(vector&lt;int&gt;&amp; nums, int k) {
    int m = *max_element(begin(nums), end(nums));
    return (m + m + k - 1) * k / 2;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2656-maximum-sum-with-exactly-k-elements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2587. Rearrange Array to Maximize Prefix Score</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 04:50:58 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9981</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;integer array&#160;nums. You can rearrange the elements of&#160;nums&#160;to&#160;any order&#160;(including the given order). Let&#160;prefix&#160;be the array containing the prefix sums of&#160;nums&#160;after rearranging it.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. You can rearrange the elements of&nbsp;<code>nums</code>&nbsp;to&nbsp;<strong>any order</strong>&nbsp;(including the given order).</p>



<p>Let&nbsp;<code>prefix</code>&nbsp;be the array containing the prefix sums of&nbsp;<code>nums</code>&nbsp;after rearranging it. In other words,&nbsp;<code>prefix[i]</code>&nbsp;is the sum of the elements from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>i</code>&nbsp;in&nbsp;<code>nums</code>&nbsp;after rearranging it. The&nbsp;<strong>score</strong>&nbsp;of&nbsp;<code>nums</code>&nbsp;is the number of positive integers in the array&nbsp;<code>prefix</code>.</p>



<p>Return&nbsp;<em>the maximum score you can achieve</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,-1,0,1,-3,3,-3]
<strong>Output:</strong> 6
<strong>Explanation:</strong> We can rearrange the array into nums = [2,3,1,-1,-3,0,-3].
prefix = [2,5,6,5,2,2,-1], so the score is 6.
It can be shown that 6 is the maximum score we can obtain.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [-2,-3,0]
<strong>Output:</strong> 0
<strong>Explanation:</strong> Any rearrangement of the array will result in a score of 0.
</pre>



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



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



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



<p>Sort the numbers in descending order.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxScore(vector&lt;int&gt;&amp; nums) {
    sort(rbegin(nums), rend(nums));
    int ans = 0;
    for (long i = 0, s = 0; i &lt; nums.size(); ++i) {
      s += nums[i];
      if (s &lt;= 0) break;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2554. Maximum Number of Integers to Choose From a Range I</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2554-maximum-number-of-integers-to-choose-from-a-range-i/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2554-maximum-number-of-integers-to-choose-from-a-range-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 14 Feb 2023 00:19:54 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9954</guid>

					<description><![CDATA[You are given an integer array&#160;banned&#160;and two integers&#160;n&#160;and&#160;maxSum. You are choosing some number of integers following the below rules: The chosen integers have to be&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>banned</code>&nbsp;and two integers&nbsp;<code>n</code>&nbsp;and&nbsp;<code>maxSum</code>. You are choosing some number of integers following the below rules:</p>



<ul class="wp-block-list"><li>The chosen integers have to be in the range&nbsp;<code>[1, n]</code>.</li><li>Each integer can be chosen&nbsp;<strong>at most once</strong>.</li><li>The chosen integers should not be in the array&nbsp;<code>banned</code>.</li><li>The sum of the chosen integers should not exceed&nbsp;<code>maxSum</code>.</li></ul>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;number of integers you can choose following the mentioned rules</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> banned = [1,6,5], n = 5, maxSum = 6
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can choose the integers 2 and 4.
2 and 4 are from the range [1, 5], both did not appear in banned, and their sum is 6, which did not exceed maxSum.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> banned = [1,2,3,4,5,6,7], n = 8, maxSum = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> You cannot choose any integer while following the mentioned conditions.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> banned = [11], n = 7, maxSum = 50
<strong>Output:</strong> 7
<strong>Explanation:</strong> You can choose the integers 1, 2, 3, 4, 5, 6, and 7.
They are from the range [1, 7], all did not appear in banned, and their sum is 28, which did not exceed maxSum.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= banned.length &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= banned[i], n &lt;= 10<sup>4</sup></code></li><li><code>1 &lt;= maxSum &lt;= 10<sup>9</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution 1: Greedy + HashSet</strong></h2>



<p>We would like to use the smallest numbers possible. Store all the banned numbers into a hashset, and enumerate numbers from 1 to n and check whether we can use that number.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxCount(vector&lt;int&gt;&amp; banned, int n, int maxSum) {
    unordered_set&lt;int&gt; m(begin(banned), end(banned));
    int ans = 0;    
    for (int i = 1, j = 0, sum = 0; i &lt;= n; ++i) {
      if (sum + i &gt; maxSum) break;
      if (m.count(i)) continue;
      sum += i;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>



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



<p>Sort the banned numbers. Use one pointer j and compare with the current number i.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maxCount(vector&lt;int&gt;&amp; banned, int n, int maxSum) {
    sort(begin(banned), end(banned));
    int ans = 0;    
    for (int i = 1, j = 0, sum = 0; i &lt;= n; ++i) {
      if (sum + i &gt; maxSum) break;
      while (j &lt; banned.size() &amp;&amp; banned[j] &lt; i) ++j;
      if (j &lt; banned.size() &amp;&amp; i == banned[j]) continue;
      sum += i;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2554-maximum-number-of-integers-to-choose-from-a-range-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2477. Minimum Fuel Cost to Report to the Capital</title>
		<link>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/</link>
					<comments>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 26 Nov 2022 16:41:02 +0000</pubDate>
				<category><![CDATA[Graph]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9905</guid>

					<description><![CDATA[There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&#160;n&#160;cities numbered from&#160;0&#160;to&#160;n - 1&#160;and exactly&#160;n - 1&#160;roads. The&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of&nbsp;<code>n</code>&nbsp;cities numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;and exactly&nbsp;<code>n - 1</code>&nbsp;roads. The capital city is city&nbsp;<code>0</code>. You are given a 2D integer array&nbsp;<code>roads</code>&nbsp;where&nbsp;<code>roads[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists a&nbsp;<strong>bidirectional road</strong>&nbsp;connecting cities&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>There is a meeting for the representatives of each city. The meeting is in the capital city.</p>



<p>There is a car in each city. You are given an integer&nbsp;<code>seats</code>&nbsp;that indicates the number of seats in each car.</p>



<p>A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.</p>



<p>Return&nbsp;<em>the minimum number of liters of fuel to reach the capital city</em>.</p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[0,1],[0,2],[0,3]], seats = 5
<strong>Output:</strong> 3
<strong>Explanation:</strong> 
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>2</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>3</sub> goes directly to the capital with 1 liter of fuel.
It costs 3 liters of fuel at minimum. 
It can be proven that 3 is the minimum number of liters of fuel needed.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> 
- Representative<sub>2</sub> goes directly to city 3 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to city 1 with 1 liter of fuel.
- Representative<sub>2</sub> and representative<sub>3</sub> go together to the capital with 1 liter of fuel.
- Representative<sub>1</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>5</sub> goes directly to the capital with 1 liter of fuel.
- Representative<sub>6</sub> goes directly to city 4 with 1 liter of fuel.
- Representative<sub>4</sub> and representative<sub>6</sub> go together to the capital with 1 liter of fuel.
It costs 7 liters of fuel at minimum. 
It can be proven that 7 is the minimum number of liters of fuel needed.
</pre>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> roads = [], seats = 1
<strong>Output:</strong> 0
<strong>Explanation:</strong> No representatives need to travel to the capital city.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>roads.length == n - 1</code></li><li><code>roads[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt; n</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li><code>roads</code>&nbsp;represents a valid tree.</li><li><code>1 &lt;= seats &lt;= 10<sup>5</sup></code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Greedy + DFS</strong></h2>



<p>To reach the minimum cost, we must share cars if possible, say X reps from children nodes to an intermediate node u on the way towards capital 0.  Then they all changes cars at node u, and we need (X + 1) // seats cars/fuel from u to 0.</p>



<p>We use DFS to count # of reps at each node u while accumulating the total cost.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimumFuelCost(vector&lt;vector&lt;int&gt;&gt;&amp; roads, int seats) {
    long long ans = 0;
    vector&lt;vector&lt;int&gt;&gt; g(roads.size() + 1);
    for (const vector&lt;int&gt;&amp; r : roads) {
      g[r[0]].push_back(r[1]);
      g[r[1]].push_back(r[0]);
    }
    // Returns total # of children of u.
    function&lt;int(int, int)&gt; dfs = [&amp;](int u, int p, int rep = 1) {      
      for (int v : g[u])
        if (v != p) rep += dfs(v, u);
      if (u) ans += (rep + seats - 1) / seats;
      return rep;
    };
    dfs(0, -1);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/graph/leetcode-2477-minimum-fuel-cost-to-report-to-the-capital/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2419. Longest Subarray With Maximum Bitwise AND</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2419-longest-subarray-with-maximum-bitwise-and/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2419-longest-subarray-with-maximum-bitwise-and/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 26 Sep 2022 17:09:13 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[and]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[bit]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9845</guid>

					<description><![CDATA[You are given an integer array&#160;nums&#160;of size&#160;n. Consider a&#160;non-empty&#160;subarray from&#160;nums&#160;that has the&#160;maximum&#160;possible&#160;bitwise AND. In other words, let&#160;k&#160;be the maximum value of the bitwise AND of&#160;any&#160;subarray&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;of size&nbsp;<code>n</code>.</p>



<p>Consider a&nbsp;<strong>non-empty</strong>&nbsp;subarray from&nbsp;<code>nums</code>&nbsp;that has the&nbsp;<strong>maximum</strong>&nbsp;possible&nbsp;<strong>bitwise AND</strong>.</p>



<ul class="wp-block-list"><li>In other words, let&nbsp;<code>k</code>&nbsp;be the maximum value of the bitwise AND of&nbsp;<strong>any</strong>&nbsp;subarray of&nbsp;<code>nums</code>. Then, only subarrays with a bitwise AND equal to&nbsp;<code>k</code>&nbsp;should be considered.</li></ul>



<p>Return&nbsp;<em>the length of the&nbsp;<strong>longest</strong>&nbsp;such subarray</em>.</p>



<p>The bitwise AND of an array is the bitwise AND of all the numbers in it.</p>



<p>A&nbsp;<strong>subarray</strong>&nbsp;is a contiguous sequence of elements within an array.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,3,2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
The maximum possible bitwise AND of a subarray is 3.
The longest subarray with that value is [3,3], so we return 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The maximum possible bitwise AND of a subarray is 4.
The longest subarray with that value is [4], so we return 1.
</pre>



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



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



<h2 class="wp-block-heading"><strong>Solution: Find the largest number</strong></h2>



<p>a &amp; b &lt;= a<br>a &amp; b &lt;= b<br>if b > a, a &amp; b &lt; b, we choose to start a new sequence of &#8220;b&#8221; instead of continuing with &#8220;ab&#8221;</p>



<p>Basically, we find the largest number in the array and count the longest sequence of it. Note, there will be some tricky cases like.<br>b b b b a b<br>b a b b b b<br>We need to return 4 instead of 1.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int longestSubarray(vector&lt;int&gt;&amp; nums) {
    int ans = 0;
    int best = 0;
    for (int i = 0, l = 0; i &lt; nums.size(); ++i) {
      if (nums[i] &gt; best) {
        best = nums[i]; 
        ans = l = 1;
      } else if (nums[i] == best) {
        ans = max(ans, ++l);
      } else {
        l = 0;
      }
    }    
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2419-longest-subarray-with-maximum-bitwise-and/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2405. Optimal Partition of String</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Sep 2022 15:05:35 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[bitmask]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9807</guid>

					<description><![CDATA[Given a string&#160;s, partition the string into one or more&#160;substrings&#160;such that the characters in each substring are&#160;unique. That is, no letter appears in a single&#8230;]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe title="花花酱 LeetCode 2405. Optimal Partition of String- 刷题找工作 EP401" width="500" height="281" src="https://www.youtube.com/embed/cKjQNbcSX0s?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
</div></figure>



<p>Given a string&nbsp;<code>s</code>, partition the string into one or more&nbsp;<strong>substrings</strong>&nbsp;such that the characters in each substring are&nbsp;<strong>unique</strong>. That is, no letter appears in a single substring more than&nbsp;<strong>once</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of substrings in such a partition.</em></p>



<p>Note that each character should belong to exactly one substring in a partition.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "abacaba"
<strong>Output:</strong> 4
<strong>Explanation:</strong>
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "ssssss"
<strong>Output:</strong> 6
<strong>Explanation:
</strong>The only valid partition is ("s","s","s","s","s","s").
</pre>



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



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



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



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s1.png"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s1.png" alt="" class="wp-image-9812" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-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/09/lc-2405-ep401-s2.png"><img decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s2.png" alt="" class="wp-image-9813" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/09/lc-2405-ep401-s2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></figure>



<p>Extend the cur string as long as possible unless a duplicate character occurs.</p>



<p>You can use hashtable / array or bitmask to mark whether a character has been seen so far.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int partitionString(string s) {
    unordered_set&lt;char&gt; m;
    int ans = 0;
    for (char c : s) {
      if (m.insert(c).second) continue;
      m.clear();
      m.insert(c);
      ++ans;
    }
    return ans + 1;
  }
};</pre>
</div></div>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int partitionString(string s) {
    vector&lt;int&gt; m(26);
    int ans = 0;
    for (char c : s) {
      if (++m[c - 'a'] == 1) continue;
      fill(begin(m), end(m), 0);
      m[c - 'a'] = 1;
      ++ans;
    }
    return ans + 1;
  }
};</pre>
</div></div>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int partitionString(string s) {
    int mask = 0;
    int ans = 0;
    for (char c : s) {
      if (mask &amp; (1 &lt;&lt; (c - 'a'))) {
        mask = 0;        
        ++ans;
      }
      mask |= 1 &lt;&lt; (c - 'a');
    }
    return ans + 1;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2405-optimal-partition-of-string/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2242. Maximum Score of a Node Sequence</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 17 Apr 2022 06:16:40 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[set]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9662</guid>

					<description><![CDATA[There is an&#160;undirected&#160;graph with&#160;n&#160;nodes, numbered from&#160;0&#160;to&#160;n - 1. You are given a&#160;0-indexed&#160;integer array&#160;scores&#160;of length&#160;n&#160;where&#160;scores[i]&#160;denotes the score of node&#160;i. You are also given a 2D integer&#8230;]]></description>
										<content:encoded><![CDATA[
<p>There is an&nbsp;<strong>undirected</strong>&nbsp;graph with&nbsp;<code>n</code>&nbsp;nodes, numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>.</p>



<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>scores</code>&nbsp;of length&nbsp;<code>n</code>&nbsp;where&nbsp;<code>scores[i]</code>&nbsp;denotes the score of node&nbsp;<code>i</code>. You are also given a 2D integer array&nbsp;<code>edges</code>&nbsp;where&nbsp;<code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code>&nbsp;denotes that there exists an&nbsp;<strong>undirected</strong>&nbsp;edge connecting nodes&nbsp;<code>a<sub>i</sub></code>&nbsp;and&nbsp;<code>b<sub>i</sub></code>.</p>



<p>A node sequence is&nbsp;<strong>valid</strong>&nbsp;if it meets the following conditions:</p>



<ul class="wp-block-list"><li>There is an edge connecting every pair of&nbsp;<strong>adjacent</strong>&nbsp;nodes in the sequence.</li><li>No node appears more than once in the sequence.</li></ul>



<p>The score of a node sequence is defined as the&nbsp;<strong>sum</strong>&nbsp;of the scores of the nodes in the sequence.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum score</strong>&nbsp;of a valid node sequence with a length of&nbsp;</em><code>4</code><em>.&nbsp;</em>If no such sequence exists, return<em>&nbsp;</em><code>-1</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/04/15/ex1new3.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [5,2,9,8,4], edges = [[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]
<strong>Output:</strong> 24
<strong>Explanation:</strong> The figure above shows the graph and the chosen node sequence [0,1,2,3].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences [3,1,2,0] and [1,0,2,3] are also valid and have a score of 24.
The sequence [0,3,2,4] is not valid since no edge connects nodes 0 and 3.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2022/03/17/ex2.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> scores = [9,20,6,4,11,12], edges = [[0,3],[5,3],[2,4],[1,3]]
<strong>Output:</strong> -1
<strong>Explanation:</strong> The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.
</pre>



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



<ul class="wp-block-list"><li><code>n == scores.length</code></li><li><code>4 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li><li><code>1 &lt;= scores[i] &lt;= 10<sup>8</sup></code></li><li><code>0 &lt;= edges.length &lt;= 5 * 10<sup>4</sup></code></li><li><code>edges[i].length == 2</code></li><li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt;= n - 1</code></li><li><code>a<sub>i</sub>&nbsp;!= b<sub>i</sub></code></li><li>There are no duplicate edges.</li></ul>



<h2 class="wp-block-heading"><strong>Solution: Greedy / Top3 neighbors</strong></h2>



<figure class="wp-block-image size-full"><a href="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png" alt="" class="wp-image-9667" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-1-768x432.png 768w" sizes="auto, (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/04/lc2242-ep396-2.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png" alt="" class="wp-image-9668" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-2-768x432.png 768w" sizes="auto, (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/04/lc2242-ep396-3.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png" alt="" class="wp-image-9669" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-3-768x432.png 768w" sizes="auto, (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/04/lc2242-ep396-4.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png" alt="" class="wp-image-9671" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-4-768x432.png 768w" sizes="auto, (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/04/lc2242-ep396-5.png"><img loading="lazy" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png" alt="" class="wp-image-9673" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2022/04/lc2242-ep396-5-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></a></figure>



<p>Since |E| is already 5*10<sup>4</sup>, we can&#8217;t enumerate all possible sequences. We must do in O(|E|) or O(|E|log|E|).</p>



<p>Enumerate all the edges, we have a pair of node a, b. To get the optimal answer, we just need to find the largest neighbor of a and b, which we call c, d respectively. Just need to make sure a, b, c, d are unique. i.e. c != d, c != b and d != a. Since the a&#8217;s largest neighbor can be either b or d. We can&#8217;t just store the largest neighbor, but top 3 instead for each node to avoid duplications.</p>



<p>Time complexity: O(|E|*9)<br>Space complexity: O(|V|*3)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumScore(vector&lt;int&gt;&amp; scores, vector&lt;vector&lt;int&gt;&gt;&amp; edges) {
    const int n = scores.size();
    vector&lt;set&lt;pair&lt;int, int&gt;&gt;&gt; top3(n);
    for (const auto&amp; e : edges) {      
      top3[e[0]].emplace(scores[e[1]], e[1]);
      top3[e[1]].emplace(scores[e[0]], e[0]);
      if (top3[e[0]].size() &gt; 3) top3[e[0]].erase(begin(top3[e[0]]));
      if (top3[e[1]].size() &gt; 3) top3[e[1]].erase(begin(top3[e[1]]));
    }
    int ans = -1;
    for (const auto&amp; e : edges) {
      const int a = e[0], b = e[1], sa = scores[a], sb = scores[b];
      for (const auto&amp; [sc, c] : top3[a])
        for (const auto&amp; [sd, d] : top3[b])          
          if (sa + sb + sc + sd &gt; ans &amp;&amp; c != b &amp;&amp; c != d &amp;&amp; d != a)
            ans = sa + sb + sc + sd;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2242-maximum-score-of-a-node-sequence/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2233. Maximum Product After K Increments</title>
		<link>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/</link>
					<comments>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 10 Apr 2022 06:38:03 +0000</pubDate>
				<category><![CDATA[Priority Queue]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[priority queue]]></category>
		<category><![CDATA[product]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9640</guid>

					<description><![CDATA[You are given an array of non-negative integers&#160;nums&#160;and an integer&#160;k. In one operation, you may choose&#160;any&#160;element from&#160;nums&#160;and&#160;increment&#160;it by&#160;1. Return&#160;the&#160;maximum&#160;product&#160;of&#160;nums&#160;after&#160;at most&#160;k&#160;operations.&#160;Since the answer may be very&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array of non-negative integers&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. In one operation, you may choose&nbsp;<strong>any</strong>&nbsp;element from&nbsp;<code>nums</code>&nbsp;and&nbsp;<strong>increment</strong>&nbsp;it by&nbsp;<code>1</code>.</p>



<p>Return<em>&nbsp;the&nbsp;<strong>maximum</strong>&nbsp;<strong>product</strong>&nbsp;of&nbsp;</em><code>nums</code><em>&nbsp;after&nbsp;<strong>at most</strong>&nbsp;</em><code>k</code><em>&nbsp;operations.&nbsp;</em>Since the answer may be very large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,4], k = 5
<strong>Output:</strong> 20
<strong>Explanation:</strong> Increment the first number 5 times.
Now nums = [5, 4], with a product of 5 * 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [6,3,3,2], k = 2
<strong>Output:</strong> 216
<strong>Explanation:</strong> Increment the second number 1 time and increment the fourth number 1 time.
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.
</pre>



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



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



<h2 class="wp-block-heading"><strong>Solution: priority queue</strong></h2>



<p>Always increment the smallest number. Proof?</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int maximumProduct(vector&lt;int&gt;&amp; nums, int k) {
    constexpr int kMod = 1e9 + 7;
    priority_queue&lt;int, vector&lt;int&gt;, greater&lt;int&gt;&gt; q(begin(nums), end(nums));
    while (k--) {
      const int n = q.top(); 
      q.pop();
      q.push(n + 1);
    }
    long long ans = 1;
    while (!q.empty()) {
      ans *= q.top(); q.pop();
      ans %= kMod;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/priority-queue/leetcode-2233-maximum-product-after-k-increments/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2224. Minimum Number of Operations to Convert Time</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Apr 2022 04:46:31 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[time]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9617</guid>

					<description><![CDATA[You are given two strings&#160;current&#160;and&#160;correct&#160;representing two&#160;24-hour times. 24-hour times are formatted as&#160;"HH:MM", where&#160;HH&#160;is between&#160;00&#160;and&#160;23, and&#160;MM&#160;is between&#160;00&#160;and&#160;59. The earliest 24-hour time is&#160;00:00, and the latest is&#160;23:59.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two strings&nbsp;<code>current</code>&nbsp;and&nbsp;<code>correct</code>&nbsp;representing two&nbsp;<strong>24-hour times</strong>.</p>



<p>24-hour times are formatted as&nbsp;<code>"HH:MM"</code>, where&nbsp;<code>HH</code>&nbsp;is between&nbsp;<code>00</code>&nbsp;and&nbsp;<code>23</code>, and&nbsp;<code>MM</code>&nbsp;is between&nbsp;<code>00</code>&nbsp;and&nbsp;<code>59</code>. The earliest 24-hour time is&nbsp;<code>00:00</code>, and the latest is&nbsp;<code>23:59</code>.</p>



<p>In one operation you can increase the time&nbsp;<code>current</code>&nbsp;by&nbsp;<code>1</code>,&nbsp;<code>5</code>,&nbsp;<code>15</code>, or&nbsp;<code>60</code>&nbsp;minutes. You can perform this operation&nbsp;<strong>any</strong>&nbsp;number of times.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum number of operations</strong>&nbsp;needed to convert&nbsp;</em><code>current</code><em>&nbsp;to&nbsp;</em><code>correct</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> current = "02:30", correct = "04:35"
<strong>Output:</strong> 3
<strong>Explanation:
</strong>We can convert current to correct in 3 operations as follows:
- Add 60 minutes to current. current becomes "03:30".
- Add 60 minutes to current. current becomes "04:30".
- Add 5 minutes to current. current becomes "04:35".
It can be proven that it is not possible to convert current to correct in fewer than 3 operations.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> current = "11:00", correct = "11:01"
<strong>Output:</strong> 1
<strong>Explanation:</strong> We only have to add one minute to current, so the minimum number of operations needed is 1.
</pre>



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



<ul class="wp-block-list"><li><code>current</code>&nbsp;and&nbsp;<code>correct</code>&nbsp;are in the format&nbsp;<code>"HH:MM"</code></li><li><code>current &lt;= correct</code></li></ul>



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



<p>Start with 60, then 15, 5 and finally increase 1 minute a time.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int convertTime(string current, string correct) {
    auto getMinute = [](string_view t) {
      return (t[0] - '0') * 10 * 60 
             + (t[1] - '0') * 60 
             + (t[3] - '0') * 10 
             + (t[4] - '0');
    };
    
    int t1 = getMinute(current);
    int t2 = getMinute(correct);
    int ans = 0;    
    for (int d : {60, 15, 5, 1})
      while (t2 - t1 &gt;= d) {
        ++ans;
        t1 += d;
      }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2224-minimum-number-of-operations-to-convert-time/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2208. Minimum Operations to Halve Array Sum</title>
		<link>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 21 Mar 2022 12:21:32 +0000</pubDate>
				<category><![CDATA[Heap]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[heap]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(nlogn)]]></category>
		<category><![CDATA[priority_queue]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9580</guid>

					<description><![CDATA[You are given an array&#160;nums&#160;of positive integers. In one operation, you can choose&#160;any&#160;number from&#160;nums&#160;and reduce it to&#160;exactly&#160;half the number. (Note that you may choose this&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an array&nbsp;<code>nums</code>&nbsp;of positive integers. In one operation, you can choose&nbsp;<strong>any</strong>&nbsp;number from&nbsp;<code>nums</code>&nbsp;and reduce it to&nbsp;<strong>exactly</strong>&nbsp;half the number. (Note that you may choose this reduced number in future operations.)</p>



<p>Return<em>&nbsp;the&nbsp;<strong>minimum</strong>&nbsp;number of operations to reduce the sum of&nbsp;</em><code>nums</code><em>&nbsp;by&nbsp;<strong>at least</strong>&nbsp;half.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,19,8,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The initial sum of nums is equal to 5 + 19 + 8 + 1 = 33.
The following is one of the ways to reduce the sum by at least half:
Pick the number 19 and reduce it to 9.5.
Pick the number 9.5 and reduce it to 4.75.
Pick the number 8 and reduce it to 4.
The final array is [5, 4.75, 4, 1] with a total sum of 5 + 4.75 + 4 + 1 = 14.75. 
The sum of nums has been reduced by 33 - 14.75 = 18.25, which is at least half of the initial sum, 18.25 &gt;= 33/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,8,20]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The initial sum of nums is equal to 3 + 8 + 20 = 31.
The following is one of the ways to reduce the sum by at least half:
Pick the number 20 and reduce it to 10.
Pick the number 10 and reduce it to 5.
Pick the number 3 and reduce it to 1.5.
The final array is [1.5, 8, 5] with a total sum of 1.5 + 8 + 5 = 14.5. 
The sum of nums has been reduced by 31 - 14.5 = 16.5, which is at least half of the initial sum, 16.5 &gt;= 31/2 = 16.5.
Overall, 3 operations were used so we return 3.
It can be shown that we cannot reduce the sum by at least half in less than 3 operations.
</pre>



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



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



<h2 class="wp-block-heading"><strong>Solution: Greedy + PriorityQueue/Max Heap</strong></h2>



<p>Always half the largest number, put all the numbers onto a max heap (priority queue), extract the largest one, and put reduced number back.</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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int halveArray(vector&lt;int&gt;&amp; nums) {
    double sum = accumulate(begin(nums), end(nums), 0.0);
    priority_queue&lt;double&gt; q;
    for (int num : nums) q.push(num);
    int ans = 0;
    for (double cur = sum; cur &gt; sum / 2; ++ans) {    
      double num = q.top(); q.pop();
      cur -= num / 2;
      q.push(num / 2);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/heap/leetcode-2208-minimum-operations-to-halve-array-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2195. Append K Integers With Minimal Sum</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 08 Mar 2022 11:25:58 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[sorting]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9550</guid>

					<description><![CDATA[You are given an integer array&#160;nums&#160;and an integer&#160;k. Append&#160;k&#160;unique positive&#160;integers that do&#160;not&#160;appear in&#160;nums&#160;to&#160;nums&#160;such that the resulting total sum is&#160;minimum. Return&#160;the sum of the&#160;k&#160;integers appended to&#160;nums.&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;and an integer&nbsp;<code>k</code>. Append&nbsp;<code>k</code>&nbsp;<strong>unique positive</strong>&nbsp;integers that do&nbsp;<strong>not</strong>&nbsp;appear in&nbsp;<code>nums</code>&nbsp;to&nbsp;<code>nums</code>&nbsp;such that the resulting total sum is&nbsp;<strong>minimum</strong>.</p>



<p>Return<em>&nbsp;the sum of the</em>&nbsp;<code>k</code>&nbsp;<em>integers appended to</em>&nbsp;<code>nums</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,25,10,25], k = 2
<strong>Output:</strong> 5
<strong>Explanation:</strong> The two unique positive integers that do not appear in nums which we append are 2 and 3.
The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.
The sum of the two integers appended is 2 + 3 = 5, so we return 5.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [5,6], k = 6
<strong>Output:</strong> 25
<strong>Explanation:</strong> The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.
The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum. 
The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.
</pre>



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



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



<h2 class="wp-block-heading"><strong>Solution: Greedy + Math, fill the gap</strong></h2>



<p>Sort all the numbers and remove duplicated ones, and fill the gap between two neighboring numbers.<br>e.g. [15, 3, 8, 8] => sorted = [3, 8, 15] <br>fill 0->3, 1,2, sum = ((0 + 1) + (3-1)) * (3-0-1) / 2 = 3<br>fill 3->8, 4, 5, 6, 7, <meta charset="utf-8">sum = ((3 + 1) + (8-1)) * (8-3-1) / 2 = 22<br>fill 8->15, 9, 10, &#8230;, 14, &#8230;<br>fill 15->inf, 16, 17, &#8230;</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  long long minimalKSum(vector&lt;int&gt;&amp; nums, int k) {    
    sort(begin(nums), end(nums));
    long long ans = 0;
    long long p = 0;
    for (int c : nums) {
      if (c == p) continue;
      long long n = min((long long)k, c - p - 1);
      ans += (p + 1 + p + n) * n / 2; 
      k -= n;
      p = c;
    }
    ans += (p + 1 + p + k) * k / 2;
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2195-append-k-integers-with-minimal-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2178. Maximum Split of Positive Even Integers</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2178-maximum-split-of-positive-even-integers/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2178-maximum-split-of-positive-even-integers/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Mar 2022 06:31:22 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9542</guid>

					<description><![CDATA[You are given an integer&#160;finalSum. Split it into a sum of a&#160;maximum&#160;number of&#160;unique&#160;positive even integers. For example, given&#160;finalSum = 12, the following splits are&#160;valid&#160;(unique positive&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer&nbsp;<code>finalSum</code>. Split it into a sum of a&nbsp;<strong>maximum</strong>&nbsp;number of&nbsp;<strong>unique</strong>&nbsp;positive even integers.</p>



<ul class="wp-block-list"><li>For example, given&nbsp;<code>finalSum = 12</code>, the following splits are&nbsp;<strong>valid</strong>&nbsp;(unique positive even integers summing up to&nbsp;<code>finalSum</code>):&nbsp;<code>(12)</code>,&nbsp;<code>(2 + 10)</code>,&nbsp;<code>(2 + 4 + 6)</code>, and&nbsp;<code>(4 + 8)</code>. Among them,&nbsp;<code>(2 + 4 + 6)</code>&nbsp;contains the maximum number of integers. Note that&nbsp;<code>finalSum</code>&nbsp;cannot be split into&nbsp;<code>(2 + 2 + 4 + 4)</code>&nbsp;as all the numbers should be unique.</li></ul>



<p>Return&nbsp;<em>a list of integers that represent a valid split containing a&nbsp;<strong>maximum</strong>&nbsp;number of integers</em>. If no valid split exists for&nbsp;<code>finalSum</code>, return&nbsp;<em>an&nbsp;<strong>empty</strong>&nbsp;list</em>. You may return the integers in&nbsp;<strong>any</strong>&nbsp;order.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> finalSum = 12
<strong>Output:</strong> [2,4,6]
<strong>Explanation:</strong> The following are valid splits: <code>(12)</code>, <code>(2 + 10)</code>, <code>(2 + 4 + 6)</code>, and <code>(4 + 8)</code>.
(2 + 4 + 6) has the maximum number of integers, which is 3. Thus, we return [2,4,6].
Note that [2,6,4], [6,2,4], etc. are also accepted.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> finalSum = 7
<strong>Output:</strong> []
<strong>Explanation:</strong> There are no valid splits for the given finalSum.
Thus, we return an empty array.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> finalSum = 28
<strong>Output:</strong> [6,8,2,12]
<strong>Explanation:</strong> The following are valid splits: <code>(2 + 26)</code>, <code>(6 + 8 + 2 + 12)</code>, and <code>(4 + 24)</code>. 
<code>(6 + 8 + 2 + 12)</code> has the maximum number of integers, which is 4. Thus, we return [6,8,2,12].
Note that [10,2,4,12], [6,2,4,16], etc. are also accepted.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= finalSum &lt;= 10<sup>10</sup></code></li></ul>



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



<p>The get the maximum number of elements, we must use the smallest numbers.</p>



<p>[2, 4, 6, &#8230;, 2k, x], where x > 2k<br>let s = 2 + 4 + &#8230; + 2k, x = num &#8211; s<br>since num is odd and s is also odd, so thus x = num &#8211; s.</p>



<p>Time complexity: O(sqrt(num)) for constructing outputs.<br>Space complexity: O(1)</p>



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;long long&gt; maximumEvenSplit(long long finalSum) {
    if (finalSum &amp; 1) return {};
    vector&lt;long long&gt; ans;
    long long s = 0;
    for (long long i = 2; s + i &lt;= finalSum; s += i, i += 2)
      ans.push_back(i);
    ans.back() += (finalSum - s);
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2178-maximum-split-of-positive-even-integers/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
