<?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/category/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 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 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 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>
		<item>
		<title>花花酱 LeetCode 2182. Construct String With Repeat Limit</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2182-construct-string-with-repeat-limit/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2182-construct-string-with-repeat-limit/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 03 Mar 2022 12:09:52 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9526</guid>

					<description><![CDATA[You are given a string&#160;s&#160;and an integer&#160;repeatLimit. Construct a new string&#160;repeatLimitedString&#160;using the characters of&#160;s&#160;such that no letter appears&#160;more than&#160;repeatLimit&#160;times&#160;in a row. You do&#160;not&#160;have to use&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a string&nbsp;<code>s</code>&nbsp;and an integer&nbsp;<code>repeatLimit</code>. Construct a new string&nbsp;<code>repeatLimitedString</code>&nbsp;using the characters of&nbsp;<code>s</code>&nbsp;such that no letter appears&nbsp;<strong>more than</strong>&nbsp;<code>repeatLimit</code>&nbsp;times&nbsp;<strong>in a row</strong>. You do&nbsp;<strong>not</strong>&nbsp;have to use all characters from&nbsp;<code>s</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>lexicographically largest</strong>&nbsp;</em><code>repeatLimitedString</code>&nbsp;<em>possible</em>.</p>



<p>A string&nbsp;<code>a</code>&nbsp;is&nbsp;<strong>lexicographically larger</strong>&nbsp;than a string&nbsp;<code>b</code>&nbsp;if in the first position where&nbsp;<code>a</code>&nbsp;and&nbsp;<code>b</code>&nbsp;differ, string&nbsp;<code>a</code>&nbsp;has a letter that appears later in the alphabet than the corresponding letter in&nbsp;<code>b</code>. If the first&nbsp;<code>min(a.length, b.length)</code>&nbsp;characters do not differ, then the longer string is the lexicographically larger one.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "cczazcc", repeatLimit = 3
<strong>Output:</strong> "zzcccac"
<strong>Explanation:</strong> We use all of the characters from s to construct the repeatLimitedString "zzcccac".
The letter 'a' appears at most 1 time in a row.
The letter 'c' appears at most 3 times in a row.
The letter 'z' appears at most 2 times in a row.
Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
The string is the lexicographically largest repeatLimitedString possible so we return "zzcccac".
Note that the string "zzcccca" is lexicographically larger but the letter 'c' appears more than 3 times in a row, so it is not a valid repeatLimitedString.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "aababab", repeatLimit = 2
<strong>Output:</strong> "bbabaa"
<strong>Explanation:</strong> We use only some of the characters from s to construct the repeatLimitedString "bbabaa". 
The letter 'a' appears at most 2 times in a row.
The letter 'b' appears at most 2 times in a row.
Hence, no letter appears more than repeatLimit times in a row and the string is a valid repeatLimitedString.
The string is the lexicographically largest repeatLimitedString possible so we return "bbabaa".
Note that the string "bbabaaa" is lexicographically larger but the letter 'a' appears more than 2 times in a row, so it is not a valid repeatLimitedString.
</pre>



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



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



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



<p>Adding one letter at a time, find the largest one that can be used.</p>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  string repeatLimitedString(string s, int repeatLimit) {
    vector&lt;int&gt; m(26);
    for (char c : s) ++m[c - 'a'];
    string ans;
    int count = 0;
    int last = -1;
    while (true) {
      bool found = false;      
      for (int i = 25; i &gt;= 0 &amp;&amp; !found; --i)
        if (m[i] &amp;&amp; (count &lt; repeatLimit || last != i)) {
          ans += 'a' + i;
          count = (last == i) * count + 1;
          --m[i];
          last = i;
          found = true;          
        }
      if (!found) break;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2182-construct-string-with-repeat-limit/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2170. Minimum Operations to Make the Array Alternating</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2170-minimum-operations-to-make-the-array-alternating/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2170-minimum-operations-to-make-the-array-alternating/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Feb 2022 13:44:11 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[alternating]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9496</guid>

					<description><![CDATA[You are given a&#160;0-indexed&#160;array&#160;nums&#160;consisting of&#160;n&#160;positive integers. The array&#160;nums&#160;is called&#160;alternating&#160;if: nums[i - 2] == nums[i], where&#160;2 &#60;= i &#60;= n - 1. nums[i - 1] !=&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array&nbsp;<code>nums</code>&nbsp;consisting of&nbsp;<code>n</code>&nbsp;positive integers.</p>



<p>The array&nbsp;<code>nums</code>&nbsp;is called&nbsp;<strong>alternating</strong>&nbsp;if:</p>



<ul class="wp-block-list"><li><code>nums[i - 2] == nums[i]</code>, where&nbsp;<code>2 &lt;= i &lt;= n - 1</code>.</li><li><code>nums[i - 1] != nums[i]</code>, where&nbsp;<code>1 &lt;= i &lt;= n - 1</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>nums[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 alternating</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [3,1,3,2,4,3]
<strong>Output:</strong> 3
<strong>Explanation:</strong>
One way to make the array alternating is by converting it to [3,1,3,<strong>1</strong>,<strong>3</strong>,<strong>1</strong>].
The number of operations required in this case is 3.
It can be proven that it is not possible to make the array alternating in less than 3 operations. 
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,2,2,2]
<strong>Output:</strong> 2
<strong>Explanation:</strong>
One way to make the array alternating is by converting it to [1,2,<strong>1</strong>,2,<strong>1</strong>].
The number of operations required in this case is 2.
Note that the array cannot be converted to [<strong>2</strong>,2,2,2,2] because in this case nums[0] == nums[1] which violates the conditions of an alternating array.
</pre>



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



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



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



<p>Count and sort the frequency of numbers at odd and even positions.</p>



<p>Case 1: top frequency numbers are different, change the rest of numbers to them respectively.<br>Case 2: top frequency numbers are the same, compare top 1 odd + top 2 even vs top 2 even + top 1 odd.</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 minimumOperations(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    if (n == 1) return 0;
    unordered_map&lt;int, int&gt; odd, even;
    for (int i = 0; i &lt; n; ++i)
      ((i &amp; 1 ? odd : even)[nums[i]])++;
    vector&lt;pair&lt;int, int&gt;&gt; o, e;
    for (const auto [k, v] : odd)
      o.emplace_back(v, k);
    for (const auto [k, v] : even)
      e.emplace_back(v, k);
    sort(rbegin(o), rend(o));
    sort(rbegin(e), rend(e));        
    if (o[0].second != e[0].second) 
      return n - o[0].first - e[0].first;    
    int mo = o[0].first + (e.size() &gt; 1 ? e[1].first : 0);
    int me = e[0].first + (o.size() &gt; 1 ? o[1].first : 0);
    return n - max(mo, me);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2170-minimum-operations-to-make-the-array-alternating/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2144. Minimum Cost of Buying Candies With Discount</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2144-minimum-cost-of-buying-candies-with-discount/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2144-minimum-cost-of-buying-candies-with-discount/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 31 Jan 2022 02:45:51 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[greedy]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9452</guid>

					<description><![CDATA[A shop is selling candies at a discount. For&#160;every two&#160;candies sold, the shop gives a&#160;third&#160;candy for&#160;free. The customer can choose&#160;any&#160;candy to take away for free&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A shop is selling candies at a discount. For&nbsp;<strong>every two</strong>&nbsp;candies sold, the shop gives a&nbsp;<strong>third</strong>&nbsp;candy for&nbsp;<strong>free</strong>.</p>



<p>The customer can choose&nbsp;<strong>any</strong>&nbsp;candy to take away for free as long as the cost of the chosen candy is less than or equal to the&nbsp;<strong>minimum</strong>&nbsp;cost of the two candies bought.</p>



<ul class="wp-block-list"><li>For example, if there are&nbsp;<code>4</code>&nbsp;candies with costs&nbsp;<code>1</code>,&nbsp;<code>2</code>,&nbsp;<code>3</code>, and&nbsp;<code>4</code>, and the customer buys candies with costs&nbsp;<code>2</code>&nbsp;and&nbsp;<code>3</code>, they&nbsp;can take the candy with cost&nbsp;<code>1</code>&nbsp;for free, but not the candy with cost&nbsp;<code>4</code>.</li></ul>



<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>cost</code>, where&nbsp;<code>cost[i]</code>&nbsp;denotes the cost of the&nbsp;<code>i<sup>th</sup></code>&nbsp;candy, return&nbsp;<em>the&nbsp;<strong>minimum cost</strong>&nbsp;of buying&nbsp;<strong>all</strong>&nbsp;the candies</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cost = [1,2,3]
<strong>Output:</strong> 5
<strong>Explanation:</strong> We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
The total cost of buying all candies is 2 + 3 = 5. This is the <strong>only</strong> way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cost = [6,5,7,9,2,2]
<strong>Output:</strong> 23
<strong>Explanation:</strong> The way in which we can get the minimum cost is described below:
- Buy candies with costs 9 and 7
- Take the candy with cost 6 for free
- We buy candies with costs 5 and 2
- Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> cost = [5,5]
<strong>Output:</strong> 10
<strong>Explanation:</strong> Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.
Hence, the minimum cost to buy all candies is 5 + 5 = 10.
</pre>



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



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



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



<p>Sort candies in descending order. Buy 1st, 2nd, take 3rd, buy 4th, 5th take 6th, &#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:
  int minimumCost(vector&lt;int&gt;&amp; cost) {
    sort(rbegin(cost), rend(cost));
    while (cost.size() % 3) cost.push_back(0);
    int ans = 0;
    for (int i = 0; i &lt; cost.size(); i += 3)
      ans += cost[i] + cost[i + 1];
    return ans;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2144-minimum-cost-of-buying-candies-with-discount/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2139. Minimum Moves to Reach Target Score</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 30 Jan 2022 16:00:45 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reverse]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9435</guid>

					<description><![CDATA[You are playing a game with integers. You start with the integer&#160;1&#160;and you want to reach the integer&#160;target. In one move, you can either: Increment&#160;the&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are playing a game with integers. You start with the integer&nbsp;<code>1</code>&nbsp;and you want to reach the integer&nbsp;<code>target</code>.</p>



<p>In one move, you can either:</p>



<ul class="wp-block-list"><li><strong>Increment</strong>&nbsp;the current integer by one (i.e.,&nbsp;<code>x = x + 1</code>).</li><li><strong>Double</strong>&nbsp;the current integer (i.e.,&nbsp;<code>x = 2 * x</code>).</li></ul>



<p>You can use the&nbsp;<strong>increment</strong>&nbsp;operation&nbsp;<strong>any</strong>&nbsp;number of times, however, you can only use the&nbsp;<strong>double</strong>&nbsp;operation&nbsp;<strong>at most</strong>&nbsp;<code>maxDoubles</code>&nbsp;times.</p>



<p>Given the two integers&nbsp;<code>target</code>&nbsp;and&nbsp;<code>maxDoubles</code>, return&nbsp;<em>the minimum number of moves needed to reach&nbsp;</em><code>target</code><em>&nbsp;starting with&nbsp;</em><code>1</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 5, maxDoubles = 0
<strong>Output:</strong> 4
<strong>Explanation:</strong> Keep incrementing by 1 until you reach target.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 19, maxDoubles = 2
<strong>Output:</strong> 7
<strong>Explanation:</strong> Initially, x = 1
Increment 3 times so x = 4
Double once so x = 8
Increment once so x = 9
Double again so x = 18
Increment once so x = 19
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> target = 10, maxDoubles = 4
<strong>Output:</strong> 4
<strong>Explanation:</strong>Initially, x = 1
Increment once so x = 2
Double once so x = 4
Increment once so x = 5
Double again so x = 10
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li><li><code>0 &lt;= maxDoubles &lt;= 100</code></li></ul>



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



<p>If num is odd, decrement it by 1. Divide num by 2 until maxdoubles times. Apply decrementing until 1 reached.</p>



<p>ex1: 19 (dec)-> 18 (div1)-> 9 (dec) -> 8 (div2)-> 4 <meta charset="utf-8">(dec)-> 3 <meta charset="utf-8">(dec)-> 2 <meta charset="utf-8">(dec)-> 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="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  int minMoves(int target, int maxDoubles) {
    int ans = 0;
    while (maxDoubles-- &amp;&amp; target != 1) {
      if (target &amp; 1)
        --target, ++ans;
      ++ans;
      target &gt;&gt;= 1;      
    }
    ans += (target - 1);
    return ans;
  }
};</pre>
</div></div>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-2139-minimum-moves-to-reach-target-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
