<?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>target sum Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/target-sum/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/target-sum/</link>
	<description></description>
	<lastBuildDate>Sun, 03 Jan 2021 07:37:34 +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>target sum Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/target-sum/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 1711. Count Good Meals</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-1711-count-good-meals/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-1711-count-good-meals/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Jan 2021 07:35:38 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[pairs]]></category>
		<category><![CDATA[target sum]]></category>
		<category><![CDATA[two sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7893</guid>

					<description><![CDATA[<p>A&#160;good meal&#160;is a meal that contains&#160;exactly two different food items&#160;with a sum of deliciousness equal to a power of two. You can pick&#160;any&#160;two different foods&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1711-count-good-meals/">花花酱 LeetCode 1711. Count Good Meals</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>A&nbsp;<strong>good meal</strong>&nbsp;is a meal that contains&nbsp;<strong>exactly two different food items</strong>&nbsp;with a sum of deliciousness equal to a power of two.</p>



<p>You can pick&nbsp;<strong>any</strong>&nbsp;two different foods to make a good meal.</p>



<p>Given an array of integers&nbsp;<code>deliciousness</code>&nbsp;where&nbsp;<code>deliciousness[i]</code>&nbsp;is the deliciousness of the&nbsp;<code>i<sup>​​​​​​th</sup>​​​​</code>​​​​ item of food, return&nbsp;<em>the number of different&nbsp;<strong>good meals</strong>&nbsp;you can make from this list modulo</em>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p>Note that items with different indices are considered different even if they have the same deliciousness value.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> deliciousness = [1,3,5,7,9]
<strong>Output:</strong> 4
<strong>Explanation: </strong>The good meals are (1,3), (1,7), (3,5) and, (7,9).
Their respective sums are 4, 8, 8, and 16, all of which are powers of 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> deliciousness = [1,1,1,3,3,3,7]
<strong>Output:</strong> 15
<strong>Explanation: </strong>The good meals are (1,1) with 3 ways, (1,3) with 9 ways, and (1,7) with 3 ways.</pre>



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



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



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



<p>Same idea as LeetCode 1: Two Sum</p>



<p>Use a hashtable to store the occurrences of all the numbers added so far. For a  new number x, check all possible 2^i &#8211; x. ans += freq[2^i &#8211; x] 0 &lt;= i &lt;= 21</p>



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



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

<pre class="crayon-plain-tag">class Solution {
public:
  int countPairs(vector&lt;int&gt;&amp; A) {
    constexpr int kMod = 1e9 + 7;
    unordered_map&lt;int, int&gt; m;    
    long ans = 0;
    for (int x : A) {
      for (int t = 1; t &lt;= 1 &lt;&lt; 21; t *= 2) {
        auto it = m.find(t - x);
        if (it != end(m)) ans += it-&gt;second;
      }
      ++m[x];
    }
    return ans % kMod;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def countPairs(self, deliciousness: List[int]) -&gt; int:
    sums = [1&lt;&lt;i for i in range(22)]
    m = defaultdict(int)
    ans = 0
    for x in deliciousness:
      for t in sums:
        if t - x in m: ans += m[t - x]
      m[x] += 1
    return ans % (10**9 + 7)</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-1711-count-good-meals/">花花酱 LeetCode 1711. Count Good Meals</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-1711-count-good-meals/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 14 Jun 2020 04:40:34 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[target sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=6912</guid>

					<description><![CDATA[<p>Given an array of integers&#160;arr&#160;and an integer&#160;target. You have to find&#160;two non-overlapping sub-arrays&#160;of&#160;arr&#160;each with sum equal&#160;target. There can be multiple answers so you have to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/">花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target 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 title="花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target Sum - 刷题找工作 EP335" width="500" height="375" src="https://www.youtube.com/embed/AeIxJrzx9MU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div></figure>



<p>Given an array of integers&nbsp;<code>arr</code>&nbsp;and an integer&nbsp;<code>target</code>.</p>



<p>You have to find&nbsp;<strong>two non-overlapping sub-arrays</strong>&nbsp;of&nbsp;<code>arr</code>&nbsp;each with sum equal&nbsp;<code>target</code>. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is&nbsp;<strong>minimum</strong>.</p>



<p>Return&nbsp;<em>the minimum sum of the lengths</em>&nbsp;of the two required sub-arrays, or return&nbsp;<em><strong>-1</strong></em>&nbsp;if you cannot&nbsp;find such two sub-arrays.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,2,2,4,3], target = 3
<strong>Output:</strong> 2
<strong>Explanation:</strong> Only two sub-arrays have sum = 3 ([3] and [3]). The sum of their lengths is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [7,3,4,7], target = 7
<strong>Output:</strong> 2
<strong>Explanation:</strong> Although we have three non-overlapping sub-arrays of sum = 7 ([7], [3,4] and [7]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [4,3,2,6,2,3,4], target = 6
<strong>Output:</strong> -1
<strong>Explanation:</strong> We have only one sub-array of sum = 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [5,5,4,4,5], target = 3
<strong>Output:</strong> -1
<strong>Explanation:</strong> We cannot find a sub-array of sum = 3.
</pre>



<p><strong>Example 5:</strong></p>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [3,1,1,1,5,1,2,1], target = 3
<strong>Output:</strong> 3
<strong>Explanation:</strong> Note that sub-arrays [1,2] and [2,1] cannot be an answer because they overlap.
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;= 10^5</code></li><li><code>1 &lt;= arr[i] &lt;= 1000</code></li><li><code>1 &lt;= target &lt;= 10^8</code></li></ul>



<h2><strong>Solution: Sliding Window + Best so far</strong></h2>



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



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



<ol><li>Use a sliding window to maintain a subarray whose sum is &lt;= target</li><li>When the sum of the sliding window equals to target, we found a subarray [s, e]</li><li>Update ans with it&#8217;s length + shortest subarray which ends before s.</li><li>We can use an array to store the shortest subarray which ends before s.</li></ol>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int minSumOfLengths(vector&lt;int&gt;&amp; arr, int target) {
    constexpr int kInf = 1e9;
    const int n = arr.size();
    // min_lens[i] := min length of a valid subarray ends or before i.
    vector&lt;int&gt; min_lens(n, kInf);
    int ans = kInf;
    int sum = 0;
    int s = 0;
    int min_len = kInf;
    for (int e = 0; e &lt; n; ++e) {
      sum += arr[e];
      while (sum &gt; target) sum -= arr[s++];
      if (sum == target) {       
        const int cur_len = e - s + 1;
        if (s &gt; 0 &amp;&amp; min_lens[s - 1] != kInf)
          ans = min(ans, cur_len + min_lens[s - 1]);
        min_len = min(min_len, cur_len);
      }
      min_lens[e] = min_len;
    }    
    return ans &gt;= kInf ? -1 : ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/">花花酱 LeetCode 1477. Find Two Non-overlapping Sub-arrays Each With Target 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/sliding-window/leetcode-1477-find-two-non-overlapping-sub-arrays-each-with-target-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List</title>
		<link>https://zxi.mytechroad.com/blog/list/leetcode-1171-remove-zero-sum-consecutive-nodes-from-linked-list/</link>
					<comments>https://zxi.mytechroad.com/blog/list/leetcode-1171-remove-zero-sum-consecutive-nodes-from-linked-list/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 25 Aug 2019 06:25:34 +0000</pubDate>
				<category><![CDATA[List]]></category>
		<category><![CDATA[hashtable]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[target sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5495</guid>

					<description><![CDATA[<p>Given the&#160;head&#160;of a linked list, we repeatedly delete consecutive sequences of nodes that sum to&#160;0until there are no such sequences. After doing so, return the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-1171-remove-zero-sum-consecutive-nodes-from-linked-list/">花花酱 LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Given the&nbsp;<code>head</code>&nbsp;of a linked list, we repeatedly delete consecutive sequences of nodes that sum to&nbsp;<code>0</code>until there are no such sequences.</p>



<p>After doing so, return the head of the final linked list.&nbsp; You may return any such answer.</p>



<p>(Note that in the examples below, all sequences are serializations of&nbsp;<code>ListNode</code>&nbsp;objects.)</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> head = [1,2,-3,3,1]
<strong>Output:</strong> [3,1]
<strong>Note:</strong> The answer [1,2,1] would also be accepted.
</pre>



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



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



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



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



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



<ul><li>The given linked list will contain between&nbsp;<code>1</code>&nbsp;and&nbsp;<code>1000</code>&nbsp;nodes.</li><li>Each node in the linked list has&nbsp;<code>-1000 &lt;= node.val &lt;= 1000</code>.</li></ul>



<h2><strong>Solution: HashTable</strong></h2>



<p>Similar to target sum = 0, use a hashtable to store the first ListNode* that has a given prefix sum. Whenever the same prefix sum occurs, skip all the elements between the first occurrence and current one, e.g. first_sum_x.next = curr_sum_x.next</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  ListNode* removeZeroSumSublists(ListNode* head) {
    bool done = false;
    function&lt;ListNode*(ListNode*)&gt; helper = [&amp;](ListNode* head) {
      ListNode dummy(0);
      dummy.next = head;    
      ListNode* prev = &amp;dummy;
      ListNode* curr = prev-&gt;next;
      unordered_map&lt;int, ListNode*&gt; m{{0, prev}};    
      int s = 0;
      done = true;
      while (curr) {
        s += curr-&gt;val;      
        if (m.count(s)) {
          m[s]-&gt;next = curr-&gt;next;
          done = false;
        } else {
          m[s] = curr;
        }
        prev = curr;
        curr = curr-&gt;next;
      }
      return dummy.next;
    };
    while (!done) head = helper(head);
    return head;
  }
};</pre>

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

<pre class="crayon-plain-tag"># Author: Huahua
class Solution:
  def removeZeroSumSublists(self, head: ListNode) -&gt; ListNode:
    def helper(head: ListNode):      
      dummy = ListNode(0)
      dummy.next = head
      prev, curr = dummy, dummy.next    
      s = 0
      m = {s: prev}
      done = True
      while curr:
        s += curr.val
        if s in m:
          m[s].next = curr.next
          done = False
        else:
          m[s] = curr
        prev, curr = curr, curr.next
      return dummy.next, done
    while True:
      head, done = helper(head)
      if done: return head</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/list/leetcode-1171-remove-zero-sum-consecutive-nodes-from-linked-list/">花花酱 LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List</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/list/leetcode-1171-remove-zero-sum-consecutive-nodes-from-linked-list/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
