<?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>reduction Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/reduction/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/reduction/</link>
	<description></description>
	<lastBuildDate>Tue, 17 Sep 2019 04:32:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0.8</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>reduction Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/reduction/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1191. K-Concatenation Maximum Sum</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1191-k-concatenation-maximum-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1191-k-concatenation-maximum-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Sep 2019 22:28:53 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[reduction]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5553</guid>

					<description><![CDATA[<p>Given an integer array&#160;arr&#160;and an integer&#160;k, modify the array by repeating it&#160;k&#160;times. For example, if&#160;arr&#160;= [1, 2]&#160;and&#160;k = 3&#160;then the modified array will be&#160;[1, 2,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1191-k-concatenation-maximum-sum/">花花酱 LeetCode 1191. K-Concatenation Maximum Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio"><div class="wp-block-embed__wrapper">
<iframe width="500" height="375" src="https://www.youtube.com/embed/-T19A8DvD6U?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an integer array&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>k</code>, modify the array by repeating it&nbsp;<code>k</code>&nbsp;times.</p>



<p>For example, if&nbsp;<code>arr&nbsp;= [1, 2]</code>&nbsp;and&nbsp;<code>k = 3&nbsp;</code>then the modified array will be&nbsp;<code>[1, 2, 1, 2, 1, 2]</code>.</p>



<p>Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be&nbsp;<code>0</code>&nbsp;and its sum in that case is&nbsp;<code>0</code>.</p>



<p>As the answer can be very large, return the answer&nbsp;<strong>modulo</strong>&nbsp;<code>10^9 + 7</code>.</p>



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



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



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



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



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



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



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



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



<h2><strong>Solution: DP</strong></h2>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269.png" alt="" class="wp-image-5560" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<figure class="wp-block-image"><img width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-2.png" alt="" class="wp-image-5561" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2019/09/1191-ep269-2-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



<p>This problem can be reduced to maxSubarray.<br>If k &lt; 3: return maxSubarray(arr * k)<br>ans1 = maxSubarray(arr * 1)<br>ans2 = maxSubarray(arr * 2)<br>ans = max([ans1, ans2, ans2 + sum(arr) * (k &#8211; 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="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int kConcatenationMaxSum(vector&lt;int&gt;&amp; arr, int k) {
    constexpr int kMod = 1e9 + 7;
    auto maxSum = [&amp;arr](int r) {
      long sum = 0;
      long ans = 0;
      for (int i = 0; i &lt; r; ++i) {
        for (long a : arr) {
          sum = max(0L, sum += a);          
          ans = max(ans, sum);
        }
      }
      return ans;
    };
    if (k &lt; 3) return maxSum(k) % kMod;
    long ans1 = maxSum(1);
    long ans2 = maxSum(2);    
    long sum = accumulate(begin(arr), end(arr), 0L);
    return max({ans1, ans2, ans2 + sum * (k - 2)}) % kMod;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1191-k-concatenation-maximum-sum/">花花酱 LeetCode 1191. K-Concatenation Maximum Sum</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1191-k-concatenation-maximum-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 413. Arithmetic Slices</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-413-arithmetic-slices/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-413-arithmetic-slices/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 17 Mar 2018 19:51:11 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[reduction]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2164</guid>

					<description><![CDATA[<p>题目大意：返回所有子数组中等差数列的个数。 Problem https://leetcode.com/problems/arithmetic-slices/description/ A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-413-arithmetic-slices/">花花酱 LeetCode 413. Arithmetic Slices</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>题目大意：返回所有子数组中等差数列的个数。</p>
<h1><strong>Problem</strong></h1>
<p><a href="https://leetcode.com/problems/arithmetic-slices/description/">https://leetcode.com/problems/arithmetic-slices/description/</a></p>
<p>A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.</p>
<p>For example, these are arithmetic sequence:</p>
<pre class="crayon: false">1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9</pre>
<p>The following sequence is not arithmetic.</p>
<pre class="crayon: false">1, 1, 2, 5, 7</pre>
<p>A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 &lt;= P &lt; Q &lt; N.</p>
<p>A slice (P, Q) of array A is called arithmetic if the sequence:<br />
A[P], A[p + 1], &#8230;, A[Q &#8211; 1], A[Q] is arithmetic. In particular, this means that P + 1 &lt; Q.</p>
<p>The function should return the number of arithmetic slices in the array A.</p>
<h2><b>Example:</b></h2>
<pre class="crayon: false ">A = [1, 2, 3, 4]

return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.</pre>
<h1><strong>Solution 0: Reduction</strong></h1>
<p>Reduce the problem to # of all 1 sub arrays.</p>
<p>B[i &#8211; 2] = is_slice(A[i], A[i+1], A[i+2])</p>
<p>Time Complexity: O(n)</p>
<p>Space Complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int numberOfArithmeticSlices(vector&lt;int&gt;&amp; A) {
    if (A.size() &lt; 3) return 0;
    vector&lt;int&gt; B(A.size() - 2, 0);
    for (int i = 2; i &lt; A.size() ; ++i) {      
      if (A[i - 1] - A[i - 2] == A[i] - A[i - 1])
        B[i - 2] = 1;      
    }
    return all1SubArrays(B);
  }
private:
  // return number of arrays whose values are all ones.
  int all1SubArrays(const vector&lt;int&gt;&amp; A) {
    int sum = 0;
    int curr = 0;
    for (int i = 0; i &lt; A.size(); ++i)
      if (A[i]) sum += ++curr;
      else curr = 0;
    return sum;
  }
};</pre><p></p>
<h1><strong>Solution 1: Combined</strong></h1>
<p>C++</p>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int numberOfArithmeticSlices(vector&lt;int&gt;&amp; A) {
    int sum = 0;
    int curr = 0;
    for (int i = 2; i &lt; A.size() ; ++i) {      
      if (A[i - 1] - A[i - 2] == A[i] - A[i - 1]) {
        sum += ++curr;
      } else {
        curr = 0;
      }
    }
    return sum;
  }
};</pre><p></p>
<h1><strong>Related Problems:</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/algorithms/array/leetcode-795-number-of-subarrays-with-bounded-maximum/">花花酱 LeetCode 795. Number of Subarrays with Bounded Maximum</a></li>
</ul>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-413-arithmetic-slices/">花花酱 LeetCode 413. Arithmetic Slices</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-413-arithmetic-slices/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 121. Best Time to Buy and Sell Stock</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 23 Dec 2017 01:32:19 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Easy]]></category>
		<category><![CDATA[max subarray]]></category>
		<category><![CDATA[reduction]]></category>
		<category><![CDATA[stock]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1319</guid>

					<description><![CDATA[<p>题目大意: 给你一只股票每天的价格，如果只能做一次交易（一次买进一次卖出）问你最多能赚多少钱。 Problem: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/">花花酱 LeetCode 121. Best Time to Buy and Sell Stock</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/8pVhUpF1INw?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p>题目大意: 给你一只股票每天的价格，如果只能做一次交易（一次买进一次卖出）问你最多能赚多少钱。</p>
<p><strong>Problem:</strong></p>
<p>Say you have an array for which the <i>i</i><sup>th</sup> element is the price of a given stock on day <i>i</i>.</p>
<p>If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.</pre><p>&nbsp;</p>
<p><img class="alignnone size-full wp-image-1561" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/121-ep140-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></p>
<p><strong>Idea:</strong></p>
<p>DP</p>
<p><strong>Solution 1:</strong></p>
<p>C++</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    int maxProfit(vector&lt;int&gt;&amp; prices) {
        const int n = prices.size();
        if (n &lt; 1) return 0;
        vector&lt;int&gt; min_prices(n);
        vector&lt;int&gt; max_profit(n);
        min_prices[0] = prices[0];
        max_profit[0] = 0;
        for (int i = 1; i &lt; n; ++i) {
            min_prices[i] = min(min_prices[i - 1], 
                                prices[i]);
            
            max_profit[i] = max(max_profit[i - 1], 
                                prices[i] - min_prices[i - 1]);
        }
        return max_profit[n - 1];
    }
};</pre><p>C++ / reduce to maximum subarray</p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    int maxProfit(vector&lt;int&gt;&amp; prices) {
        int n = prices.size();
        if (n &lt; 2) return 0;
        vector&lt;int&gt; gains(n - 1, 0);
        for (int i = 1; i &lt; n; ++i)
            gains[i - 1] = prices[i] - prices[i - 1];
        return max(0, maxSubArray(gains));
    }
private:
    // From LC 53. Maximum Subarray
    int maxSubArray(vector&lt;int&gt;&amp; nums) {
        vector&lt;int&gt; f(nums.size());
        f[0] = nums[0];
        
        for (int i = 1; i &lt; nums.size(); ++i)
            f[i] = max(f[i - 1] + nums[i], nums[i]);
        
        return *std::max_element(f.begin(), f.end());
    }
};</pre><p><strong>Related Problems:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-309-best-time-to-buy-and-sell-stock-with-cooldown/">花花酱 LeetCode 309. Best Time to Buy and Sell Stock with Cooldown</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/">花花酱 LeetCode 121. Best Time to Buy and Sell Stock</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-121-best-time-to-buy-and-sell-stock/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 740. Delete and Earn</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-740-delete-and-earn/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-740-delete-and-earn/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 06 Dec 2017 05:40:51 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[Medium]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[house robber]]></category>
		<category><![CDATA[reduction]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=1121</guid>

					<description><![CDATA[<p>Problem: Given an array nums of integers, you can perform operations on the array. In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-740-delete-and-earn/">花花酱 LeetCode 740. Delete and Earn</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/YzZd-bsMthk?feature=oembed" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe></p>
<p><strong>Problem:</strong></p>
<p>Given an array <code>nums</code> of integers, you can perform operations on the array.</p>
<p>In each operation, you pick any <code>nums[i]</code> and delete it to earn <code>nums[i]</code> points. After, you must delete <b>every</b>element equal to <code>nums[i] - 1</code> or <code>nums[i] + 1</code>.</p>
<p>You start with 0 points. Return the maximum number of points you can earn by applying such operations.</p>
<p><b>Example 1:</b></p><pre class="crayon-plain-tag">Input: nums = [3, 4, 2]
Output: 6
Explanation: 
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.</pre><p><b>Example 2:</b></p><pre class="crayon-plain-tag">Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation: 
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.</pre><p><b>Note:</b></p>
<ul>
<li>The length of <code>nums</code> is at most <code>20000</code>.</li>
<li>Each element <code>nums[i]</code> is an integer in the range <code>[1, 10000]</code>.</li>
</ul>
<p><ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<p><strong>Idea:</strong></p>
<p>Reduce the problem to <a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/">House Robber Problem</a></p>
<p><span style="font-weight: 400;">Key observations: If we take nums[i]</span></p>
<ol>
<li><span style="font-weight: 400;"> We can safely take all of its copies.</span></li>
<li><span style="font-weight: 400;"> We can’t take any of copies of nums[i &#8211; 1] and nums[i + 1]</span></li>
</ol>
<p><span style="font-weight: 400;">This problem is reduced to 198 House Robber.</span></p>
<p><span style="font-weight: 400;">Houses[i] has all the copies of num whose value is i.</span></p>
<p><span style="font-weight: 400;">[3 4 2] -&gt; [0 2 3 4], rob([0 </span><b>2</b><span style="font-weight: 400;"> 3 </span><b>4</b><span style="font-weight: 400;">]) = 6            </span></p>
<p><span style="font-weight: 400;">[2, 2, 3, 3, 3, 4] -&gt; [0 2*2 3*3 4], rob([0 2*2 </span><b>3*3</b><span style="font-weight: 400;"> 4]) = 9</span></p>
<p><span style="font-weight: 400;">Time complexity: O(n+r) reduction + O(r) solving rob = O(n + r)</span></p>
<p><span style="font-weight: 400;">Space complexity: O(r)</span></p>
<p><span style="font-weight: 400;">r = max(nums) &#8211; min(nums) + 1</span></p>
<p><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/740-ep125.png"><img class="alignnone size-full wp-image-1128" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/740-ep125.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/740-ep125.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/740-ep125-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/12/740-ep125-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></a></p>
<p>Time complexity: O(n + r)</p>
<p>Space complexity: O(r)</p>
<p><strong>Solution:</strong></p><pre class="crayon-plain-tag">// Author: Huahua
// Runtime: 6 ms
class Solution {
public:
    int deleteAndEarn(vector&lt;int&gt;&amp; nums) {
        if (nums.empty()) return 0;
        const auto range = minmax_element(nums.begin(), nums.end());
        const int l = *(range.first);
        const int r = *(range.second);        
        vector&lt;int&gt; points(r - l + 1, 0);
        for (const int num : nums)
            points[num - l] += num;
        return rob(points);
    }
private:
    // From LeetCode 198. House Robber
    int rob(const vector&lt;int&gt;&amp; nums) {
        int dp2 = 0;
        int dp1 = 0;
        for (int i = 0; i &lt; nums.size() ; ++i) {
            int dp = max(dp2 + nums[i], dp1);
            dp2 = dp1;
            dp1 = dp;
        }
        return dp1;
    }
};</pre><p><strong>Related Problem:</strong></p>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-198-house-robber/">花花酱 LeetCode 198. House Robber</a></li>
</ul>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-740-delete-and-earn/">花花酱 LeetCode 740. Delete and Earn</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-740-delete-and-earn/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
