<?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>sum &#8211; Huahua&#8217;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/sum/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog</link>
	<description></description>
	<lastBuildDate>Mon, 02 Mar 2026 11:20:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>

<image>
	<url>https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/cropped-photo-32x32.jpg</url>
	<title>sum &#8211; Huahua&#8217;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>LeetCode 3512. Minimum Operations to Make Array Sum Divisible by K</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-3512-minimum-operations-to-make-array-sum-divisible-by-k/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-3512-minimum-operations-to-make-array-sum-divisible-by-k/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 16 Apr 2025 01:17:03 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[mod]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10351</guid>

					<description><![CDATA[求合取余即可，余数就是答案。 Time complexity: O(n)Space complexity: O(1) [crayon-69a71f19dc3a3497967261/]]]></description>
										<content:encoded><![CDATA[
<p>求合取余即可，余数就是答案。</p>



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



<pre class="urvanov-syntax-highlighter-plain-tag">class Solution {
public:
  int minOperations(vector&lt;int&gt;&amp; nums, int k) {
    return accumulate(begin(nums), end(nums), 0) % k;
  }
};</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/math/leetcode-3512-minimum-operations-to-make-array-sum-divisible-by-k/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2395. Find Subarrays With Equal Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2395-find-subarrays-with-equal-sum%ef%bf%bc/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2395-find-subarrays-with-equal-sum%ef%bf%bc/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 07 Sep 2022 23:31:54 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9796</guid>

					<description><![CDATA[Given a&#160;0-indexed&#160;integer array&#160;nums, determine whether there exist&#160;two&#160;subarrays of length&#160;2&#160;with&#160;equal&#160;sum. Note that the two subarrays must begin at&#160;different&#160;indices. Return&#160;true&#160;if these subarrays exist, and&#160;false&#160;otherwise. A&#160;subarray&#160;is a contiguous&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, determine whether there exist&nbsp;<strong>two</strong>&nbsp;subarrays of length&nbsp;<code>2</code>&nbsp;with&nbsp;<strong>equal</strong>&nbsp;sum. Note that the two subarrays must begin at&nbsp;<strong>different</strong>&nbsp;indices.</p>



<p>Return&nbsp;<code>true</code><em>&nbsp;if these subarrays exist, and&nbsp;</em><code>false</code><em>&nbsp;otherwise.</em></p>



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,2,4]
<strong>Output:</strong> true
<strong>Explanation:</strong> The subarrays with elements [4,2] and [2,4] have the same sum of 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Output:</strong> false
<strong>Explanation:</strong> No two subarrays of size 2 have the same sum.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,0,0]
<strong>Output:</strong> true
<strong>Explanation:</strong> The subarrays [nums[0],nums[1]] and [nums[1],nums[2]] have the same sum of 0. 
Note that even though the subarrays have the same content, the two subarrays are considered different because they are in different positions in the original array.
</pre>



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



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



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



<p>Use a hashset to track all the sums seen so far.</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:
  bool findSubarrays(vector&lt;int&gt;&amp; nums) {
    unordered_set&lt;int&gt; s;
    for (int i = 1; i &lt; nums.size(); ++i)
      if (!s.emplace(nums[i] + nums[i - 1]).second) return true;    
    return false;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2395-find-subarrays-with-equal-sum%ef%bf%bc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2389. Longest Subsequence With Limited Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 01 Sep 2022 12:04:07 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9791</guid>

					<description><![CDATA[You are given an integer array&#160;nums&#160;of length&#160;n, and an integer array&#160;queries&#160;of length&#160;m. Return&#160;an array&#160;answer&#160;of length&#160;m&#160;where&#160;answer[i]&#160;is the&#160;maximum&#160;size of a&#160;subsequence&#160;that you can take from&#160;nums&#160;such that the&#160;sum&#160;of its&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>, and an integer array&nbsp;<code>queries</code>&nbsp;of length&nbsp;<code>m</code>.</p>



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



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



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



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



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



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



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



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



<h2 class="wp-block-heading"><strong>Solution: Sort + PrefixSum + Binary Search</strong></h2>



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



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

<pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; answerQueries(vector&lt;int&gt;&amp; nums, vector&lt;int&gt;&amp; queries) {    
    sort(begin(nums), end(nums));
    partial_sum(begin(nums), end(nums), begin(nums));
    vector&lt;int&gt; ans;
    for (int q : queries)
      ans.push_back(upper_bound(begin(nums), end(nums), q) - begin(nums));
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2389-longest-subsequence-with-limited-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 13 Dec 2021 02:49:45 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[query]]></category>
		<category><![CDATA[range]]></category>
		<category><![CDATA[range query]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9171</guid>

					<description><![CDATA[Problem Solution 1: Range sum query Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading"><strong><a href="http://2106. Maximum Fruits Harvested After at Most K Steps">Problem</a></strong></h2>



<p></p>



<h2 class="wp-block-heading"><strong>Solution 1: Range sum query</strong></h2>



<p>Assuming we can collect fruits in range [l, r], we need a fast query to compute the sum of those fruits.</p>



<p>Given startPos and k, we have four options:<br>1. move i steps to the left<br>2. move i steps to the left and k &#8211; i steps to the right.<br>3. move i steps to the right<br>4. move i steps to the right and k &#8211; i steps to the left.</p>



<p>We enumerate i steps and calculate maximum range [l, r] covered by each option, and collect all the fruit in that range.</p>



<p>Time complexity: O(m + k)<br>Space complexity: O(m)<br>where m = max(max(pos), startPos)</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 maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    const int m = max(startPos, (*max_element(begin(fruits), end(fruits)))[0]);
    vector&lt;int&gt; sums(m + 2);   
    for (int i = 0, j = 0; i &lt;= m; ++i) {
      sums[i + 1] += sums[i];
      while (j &lt; fruits.size() &amp;&amp; fruits[j][0] == i)        
        sums[i + 1] += fruits[j++][1];      
    }    
    int ans = 0;
    for (int s = 0; s &lt;= k; ++s) {
      if (startPos - s &gt;= 0) {
        int l = startPos - s;
        int r = min(max(startPos, l + (k - s)), m);        
        ans = max(ans, sums[r + 1] - sums[l]);
      }
      if (startPos + s &lt;= m) {
        int r = startPos + s;
        int l = max(0, min(startPos, r - (k - s)));
        ans = max(ans, sums[r + 1] - sums[l]);
      }
    }             
    return ans;
  }
};</pre>
</div></div>



<h2 class="wp-block-heading"><strong>Solution 2: Sliding Window</strong></h2>



<p>Maintain a window [l, r] such that the steps to cover [l, r] from startPos is less or equal to k.</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 maxTotalFruits(vector&lt;vector&lt;int&gt;&gt;&amp; fruits, int startPos, int k) {    
    auto steps = [&amp;](int l, int r) {
      if (r &lt;= startPos)
        return startPos - l;
      else if (l &gt;= startPos)
        return r - startPos;
      else
        return min(startPos + r - 2 * l, 2 * r - startPos - l);
    };
    int ans = 0;
    for (int r = 0, l = 0, cur = 0; r &lt; fruits.size(); ++r) {
      cur += fruits[r][1];
      while (l &lt;= r &amp;&amp; steps(fruits[l][0], fruits[r][0]) &gt; k)
        cur -= fruits[l++][1];      
      ans = max(ans, cur);
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1818. Minimum Absolute Sum Difference</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1818-minimum-absolute-sum-difference/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1818-minimum-absolute-sum-difference/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 07 Apr 2021 00:27:27 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[abs]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8325</guid>

					<description><![CDATA[You are given two positive integer arrays&#160;nums1&#160;and&#160;nums2, both of length&#160;n. The&#160;absolute sum difference&#160;of arrays&#160;nums1&#160;and&#160;nums2&#160;is defined as the&#160;sum&#160;of&#160;&#124;nums1[i] - nums2[i]&#124;&#160;for each&#160;0 &#60;= i &#60; n&#160;(0-indexed). You&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given two positive integer arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>, both of length&nbsp;<code>n</code>.</p>



<p>The&nbsp;<strong>absolute sum difference</strong>&nbsp;of arrays&nbsp;<code>nums1</code>&nbsp;and&nbsp;<code>nums2</code>&nbsp;is defined as the&nbsp;<strong>sum</strong>&nbsp;of&nbsp;<code>|nums1[i] - nums2[i]|</code>&nbsp;for each&nbsp;<code>0 &lt;= i &lt; n</code>&nbsp;(<strong>0-indexed</strong>).</p>



<p>You can replace&nbsp;<strong>at most one</strong>&nbsp;element of&nbsp;<code>nums1</code>&nbsp;with&nbsp;<strong>any</strong>&nbsp;other element in&nbsp;<code>nums1</code>&nbsp;to&nbsp;<strong>minimize</strong>&nbsp;the absolute sum difference.</p>



<p>Return the&nbsp;<em>minimum absolute sum difference&nbsp;<strong>after</strong>&nbsp;replacing at most oneelement in the array&nbsp;<code>nums1</code>.</em>&nbsp;Since the answer may be large, return it&nbsp;<strong>modulo</strong>&nbsp;<code>10<sup>9</sup>&nbsp;+ 7</code>.</p>



<p><code>|x|</code>&nbsp;is defined as:</p>



<ul class="wp-block-list"><li><code>x</code>&nbsp;if&nbsp;<code>x &gt;= 0</code>, or</li><li><code>-x</code>&nbsp;if&nbsp;<code>x &lt; 0</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,7,5], nums2 = [2,3,5]
<strong>Output:</strong> 3
<strong>Explanation: </strong>There are two possible optimal solutions:
- Replace the second element with the first: [1,<strong>7</strong>,5] =&gt; [1,<strong>1</strong>,5], or
- Replace the second element with the third: [1,<strong>7</strong>,5] =&gt; [1,<strong>5</strong>,5].
Both will yield an absolute sum difference of <code>|1-2| + (|1-3| or |5-3|) + |5-5| = </code>3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
<strong>Output:</strong> 0
<strong>Explanation: </strong>nums1 is equal to nums2 so no replacement is needed. This will result in an 
absolute sum difference of 0.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
<strong>Output:</strong> 20
<strong>Explanation: </strong>Replace the first element with the second: [<strong>1</strong>,10,4,4,2,7] =&gt; [<strong>10</strong>,10,4,4,2,7].
This yields an absolute sum difference of <code>|10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20</code>
</pre>



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



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



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



<p>Greedy won&#8217;t work, e.g. finding the max diff pair and replace it. Counter example:<br>nums1 = [7, 5], nums2 = [1, -2]<br>pair1 = abs(7 &#8211; 1) = 6<br>pair2 = abs(5 &#8211; (-2)) = 7<br>If we replace 5 with 7, we got pair2&#8242; = abs(7 &#8211; (-2)) = 9 &gt; 7.</p>



<p>Every pair of numbers can be the candidate, we just need to find the closest number for each nums2[i].</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">class Solution {
public:
  int minAbsoluteSumDiff(vector&lt;int&gt;&amp; nums1, vector&lt;int&gt;&amp; nums2) {
    constexpr int kMod = 1e9 + 7;
    const int n = nums1.size();
    long ans = 0;
    int gain = 0;
    set&lt;int&gt; s(begin(nums1), end(nums1));
    for (int i = 0; i &lt; n; ++i) {
      const int diff = abs(nums1[i] - nums2[i]);
      ans += diff;
      if (diff &lt;= gain) continue;
      auto it = s.lower_bound(nums2[i]);      
      if (it != s.end()) 
        gain = max(gain, diff - abs(*it - nums2[i]));
      if (it != s.begin()) 
        gain = max(gain, diff - abs(*prev(it) - nums2[i])); 
    }
    return (ans - gain) % kMod;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1818-minimum-absolute-sum-difference/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1672. Richest Customer Wealth</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 29 Nov 2020 09:47:42 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7733</guid>

					<description><![CDATA[You are given an&#160;m x n&#160;integer grid&#160;accounts&#160;where&#160;accounts[i][j]&#160;is the amount of money the&#160;i​​​​​​​​​​​th​​​​&#160;customer has in the&#160;j​​​​​​​​​​​th​​​​ bank. Return&#160;the&#160;wealth&#160;that the richest customer has. A customer&#8217;s&#160;wealth&#160;is the amount&#8230;]]></description>
										<content:encoded><![CDATA[
<p>You are given an&nbsp;<code>m x n</code>&nbsp;integer grid&nbsp;<code>accounts</code>&nbsp;where&nbsp;<code>accounts[i][j]</code>&nbsp;is the amount of money the&nbsp;<code>i​​​​​<sup>​​​​​​th</sup>​​​​</code>&nbsp;customer has in the&nbsp;<code>j​​​​​<sup>​​​​​​th</sup></code>​​​​ bank. Return<em>&nbsp;the&nbsp;<strong>wealth</strong>&nbsp;that the richest customer has.</em></p>



<p>A customer&#8217;s&nbsp;<strong>wealth</strong>&nbsp;is the amount of money they have in all their bank accounts. The richest customer is the customer that has the maximum&nbsp;<strong>wealth</strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> accounts = [[1,2,3],[3,2,1]]
<strong>Output:</strong> 6
<strong>Explanation</strong><strong>:</strong>
<code>1st customer has wealth = 1 + 2 + 3 = 6
</code><code>2nd customer has wealth = 3 + 2 + 1 = 6
</code>Both customers are considered the richest with a wealth of 6 each, so return 6.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> accounts = [[1,5],[7,3],[3,5]]
<strong>Output:</strong> 10
<strong>Explanation</strong>: 
1st customer has wealth = 6
2nd customer has wealth = 10 
3rd customer has wealth = 8
The 2nd customer is the richest with a wealth of 10.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> accounts = [[2,8,7],[7,1,3],[1,9,5]]
<strong>Output:</strong> 17
</pre>



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



<ul class="wp-block-list"><li><code>m ==&nbsp;accounts.length</code></li><li><code>n ==&nbsp;accounts[i].length</code></li><li><code>1 &lt;= m, n &lt;= 50</code></li><li><code>1 &lt;= accounts[i][j] &lt;= 100</code></li></ul>



<h2 class="wp-block-heading"><strong>Solution: Sum each row up</strong></h2>



<p>Time complexity: O(mn)<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 maximumWealth(vector&lt;vector&lt;int&gt;&gt;&amp; accounts) {
    int ans = 0;
    for (const vector&lt;int&gt;&amp; row : accounts)
      ans = max(ans, accumulate(begin(row), end(row), 0));
    return ans;
  }
};</pre>

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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua
class Solution:
  def maximumWealth(self, accounts: List[List[int]]) -&gt; int:
    return max(sum(account) for account in accounts)</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1672-richest-customer-wealth/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1648. Sell Diminishing-Valued Colored Balls</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-1648-sell-diminishing-valued-colored-balls/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-1648-sell-diminishing-valued-colored-balls/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Nov 2020 07:12:01 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7622</guid>

					<description><![CDATA[You have an&#160;inventory&#160;of different colored balls, and there is a customer that wants&#160;orders&#160;balls of&#160;any&#160;color. The customer weirdly values the colored balls. Each colored ball&#8217;s value&#8230;]]></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 1648. Sell Diminishing-Valued Colored Balls - 刷题找工作 EP368" width="500" height="281" src="https://www.youtube.com/embed/kBxqAnWo9Wo?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>You have an&nbsp;<code>inventory</code>&nbsp;of different colored balls, and there is a customer that wants&nbsp;<code>orders</code>&nbsp;balls of&nbsp;<strong>any</strong>&nbsp;color.</p>



<p>The customer weirdly values the colored balls. Each colored ball&#8217;s value is the number of balls&nbsp;<strong>of that color&nbsp;</strong>you currently have in your&nbsp;<code>inventory</code>. For example, if you own&nbsp;<code>6</code>&nbsp;yellow balls, the customer would pay&nbsp;<code>6</code>&nbsp;for the first yellow ball. After the transaction, there are only&nbsp;<code>5</code>&nbsp;yellow balls left, so the next yellow ball is then valued at&nbsp;<code>5</code>&nbsp;(i.e., the value of the balls decreases as you sell more to the customer).</p>



<p>You are given an integer array,&nbsp;<code>inventory</code>, where&nbsp;<code>inventory[i]</code>&nbsp;represents the number of balls of the&nbsp;<code>i<sup>th</sup></code>&nbsp;color that you initially own. You are also given an integer&nbsp;<code>orders</code>, which represents the total number of balls that the customer wants. You can sell the balls&nbsp;<strong>in any order</strong>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;total value that you can attain after selling&nbsp;</em><code>orders</code><em>&nbsp;colored balls</em>. As the answer may be too large, return it&nbsp;<strong>modulo&nbsp;</strong><code>10<sup>9&nbsp;</sup>+ 7</code>.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2020/11/05/jj.gif" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> inventory = [2,5], orders = 4
<strong>Output:</strong> 14
<strong>Explanation:</strong> Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3).
The maximum total value is 2 + 5 + 4 + 3 = 14.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> inventory = [3,5], orders = 6
<strong>Output:</strong> 19
<strong>Explanation: </strong>Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2).
The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> inventory = [2,8,4,10,6], orders = 20
<strong>Output:</strong> 110
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> inventory = [1000000000], orders = 1000000000
<strong>Output:</strong> 21
<strong>Explanation: </strong>Sell the 1st color 1000000000 times for a total value of 500000000500000000. 500000000500000000 modulo 10<sup>9 </sup>+ 7 = 21.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= inventory.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= inventory[i] &lt;= 10<sup>9</sup></code></li><li><code>1 &lt;= orders &lt;= min(sum(inventory[i]), 10<sup>9</sup>)</code></li></ul>



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



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="960" height="540" src="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1648-ep368-1.png" alt="" class="wp-image-7630" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1648-ep368-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1648-ep368-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2020/11/1648-ep368-1-768x432.png 768w" sizes="(max-width: 960px) 100vw, 960px" /></figure>



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



<ol class="wp-block-list"><li>Sort the colors by # of balls in descending order.<br>e.g. 3 7 5 1 =&gt; 7 5 3 1</li><li>Sell the color with largest number of balls until it has the same number of balls of next color<ol><li>7 5 3 1 =&gt; 6 5 3 1 =&gt; 5 5 3 1 # value = 7 + 6 = 13</li><li>5 5 3 1 =&gt; 4 4 3 1 =&gt; 3 3 3 1 # value = 13 + (5 + 4) * 2 = 31</li><li>3 3 3 1 =&gt; 2 2 2 1 =&gt; 1 1 1 1 # value = 31 + (3 + 2) * 3 = 46</li><li>1 1 1 1 =&gt; 0 0 0 0 # value = 46 + 1 * 4 = 50</li></ol></li><li>Need to handle the case if orders &lt; total balls&#8230;<br></li></ol>



<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 maxProfit(vector&lt;int&gt;&amp; inventory, int orders) {
    constexpr int kMod = 1e9 + 7;
    const int n = inventory.size();
    sort(rbegin(inventory), rend(inventory));
    long cur = inventory[0];
    long ans = 0;
    int c = 0;
    while (orders) {      
      while (c &lt; n &amp;&amp; inventory[c] == cur) ++c;
      int nxt = c == n ? 0 : inventory[c];      
      int count = min(static_cast&lt;long&gt;(orders), c * (cur - nxt));
      int t = cur - nxt;
      int r = 0;
      if (orders &lt; c * (cur - nxt)) {
        t = orders / c;
        r = orders % c;
      }
      ans = (ans + (cur + cur - t + 1) * t / 2 * c + (cur - t) * r) % kMod;
      orders -= count;
      cur = nxt;
    }
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/greedy/leetcode-1648-sell-diminishing-valued-colored-balls/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Sep 2019 04:23:10 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5534</guid>

					<description><![CDATA[Given an array of integers, return the maximum sum for a&#160;non-empty&#160;subarray (contiguous elements) with at most one element deletion.&#160;In other words, you want to choose&#8230;]]></description>
										<content:encoded><![CDATA[
<p>Given an array of integers, return the maximum sum for a&nbsp;<strong>non-empty</strong>&nbsp;subarray (contiguous elements) with at most one element deletion.&nbsp;In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the&nbsp;sum of the remaining elements is maximum possible.</p>



<p>Note that the subarray needs to be&nbsp;<strong>non-empty</strong>&nbsp;after deleting one element.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,-2,0,3]
<strong>Output:</strong> 4
<strong>Explanation: </strong>Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [1,-2,-2,3]
<strong>Output:</strong> 3
<strong>Explanation: </strong>We just choose [3] and it's the maximum sum.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [-1,-1,-1,-1]
<strong>Output:</strong> -1
<strong>Explanation:</strong>&nbsp;The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
</pre>



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



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



<p><strong>Solution: DP</strong></p>



<p>First, handle the special case: all numbers are negative, return the max one.</p>



<p>s0 = max subarray sum ends with a[i]<br>s1 = max subarray sum ends with a[i] with at most one deletion</p>



<p>whenever s0 or s1 becomes negative, reset them to 0.</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 maximumSum(vector&lt;int&gt;&amp; arr) {    
    int m = *max_element(begin(arr), end(arr));
    if (m &lt;= 0) return m;
    
    int s0 = 0;
    int s1 = 0;
    int ans = 0;
    
    for (int a : arr) {
      s1 = max(s0, s1 + a);
      s0 += a;
      ans = max(ans, max(s0, s1));
      if (s0 &lt; 0) s0 = 0;
      if (s1 &lt; 0) s1 = 0;
    }
    
    return ans;
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1186-maximum-subarray-sum-with-one-deletion/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1184. Distance Between Bus Stops</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1184-distance-between-bus-stops/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1184-distance-between-bus-stops/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 08 Sep 2019 04:12:57 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[graph]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5528</guid>

					<description><![CDATA[A bus&#160;has&#160;n&#160;stops numbered from&#160;0&#160;to&#160;n - 1&#160;that form&#160;a circle. We know the distance between all pairs of neighboring stops where&#160;distance[i]&#160;is the distance between the stops number&#160;i&#160;and&#160;(i&#8230;]]></description>
										<content:encoded><![CDATA[
<p>A bus&nbsp;has&nbsp;<code>n</code>&nbsp;stops numbered from&nbsp;<code>0</code>&nbsp;to&nbsp;<code>n - 1</code>&nbsp;that form&nbsp;a circle. We know the distance between all pairs of neighboring stops where&nbsp;<code>distance[i]</code>&nbsp;is the distance between the stops number&nbsp;<code>i</code>&nbsp;and&nbsp;<code>(i + 1) % n</code>.</p>



<p>The bus goes along both directions&nbsp;i.e. clockwise and counterclockwise.</p>



<p>Return the shortest distance between the given&nbsp;<code>start</code>&nbsp;and&nbsp;<code>destination</code>&nbsp;stops.</p>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> distance = [1,2,3,4], start = 0, destination = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong> Distance between 0 and 1 is 1 or 9, minimum is 1.</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-1.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> distance = [1,2,3,4], start = 0, destination = 2
<strong>Output:</strong> 3
<strong>Explanation:</strong> Distance between 0 and 2 is 3 or 7, minimum is 3.
</pre>



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



<figure class="wp-block-image"><img decoding="async" src="https://assets.leetcode.com/uploads/2019/09/03/untitled-diagram-1-2.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> distance = [1,2,3,4], start = 0, destination = 3
<strong>Output:</strong> 4
<strong>Explanation:</strong> Distance between 0 and 3 is 6 or 4, minimum is 4.
</pre>



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



<ul class="wp-block-list"><li><code>1 &lt;= n&nbsp;&lt;= 10^4</code></li><li><code>distance.length == n</code></li><li><code>0 &lt;= start, destination &lt; n</code></li><li><code>0 &lt;= distance[i] &lt;= 10^4</code></li></ul>



<p><strong>Solution: Summation</strong></p>



<ol class="wp-block-list"><li>compute the total sum</li><li>compute the sum from s to d, c</li><li>ans = min(c, sum &#8211; c)</li></ol>



<p>Time complexity: O(d-s)<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 distanceBetweenBusStops(vector&lt;int&gt;&amp; ds, int s, int d) {    
    if (s &gt; d) swap(s, d);
    int sum = accumulate(begin(ds), end(ds), 0);
    int d1 = accumulate(begin(ds) + s, begin(ds) + d, 0);
    return min(d1, sum - d1);
  }
};</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1184-distance-between-bus-stops/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 985. Sum of Even Numbers After Queries</title>
		<link>https://zxi.mytechroad.com/blog/simulation/leetcode-985-sum-of-even-numbers-after-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/simulation/leetcode-985-sum-of-even-numbers-after-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 03 Feb 2019 06:10:19 +0000</pubDate>
				<category><![CDATA[Simulation]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[simulation]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=4761</guid>

					<description><![CDATA[Problem We have an array&#160;A&#160;of integers, and an array&#160;queries&#160;of queries. For the&#160;i-th&#160;query&#160;val =&#160;queries[i][0], index&#160;= queries[i][1], we add&#160;val&#160;to&#160;A[index].&#160; Then, the answer to the&#160;i-th query is the&#8230;]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Problem</h2>



<p>We have an array&nbsp;<code>A</code>&nbsp;of integers, and an array&nbsp;<code>queries</code>&nbsp;of queries.</p>



<p>For the&nbsp;<code>i</code>-th&nbsp;query&nbsp;<code>val =&nbsp;queries[i][0], index&nbsp;= queries[i][1]</code>, we add&nbsp;val&nbsp;to&nbsp;<code>A[index]</code>.&nbsp; Then, the answer to the&nbsp;<code>i</code>-th query is the sum of the even values of&nbsp;<code>A</code>.</p>



<p><em>(Here, the given&nbsp;<code>index = queries[i][1]</code>&nbsp;is a 0-based index, and each query permanently modifies the array&nbsp;<code>A</code>.)</em></p>



<p>Return the answer to all queries.&nbsp; Your&nbsp;<code>answer</code>&nbsp;array should have&nbsp;<code>answer[i]</code>&nbsp;as&nbsp;the answer to the&nbsp;<code>i</code>-th query.</p>



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



<pre class="wp-block-preformatted crayon:false"><strong>Input: </strong>A = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
<strong>Output: </strong>[8,6,2,4]
<strong>Explanation: </strong>
At the beginning, the array is [1,2,3,4].
After adding 1 to A[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to A[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to A[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to A[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
</pre>



<p><strong>Note:</strong></p>



<ol class="wp-block-list"><li><code>1 &lt;= A.length &lt;= 10000</code></li><li><code>-10000 &lt;= A[i] &lt;= 10000</code></li><li><code>1 &lt;= queries.length &lt;= 10000</code></li><li><code>-10000 &lt;= queries[i][0] &lt;= 10000</code></li><li><code>0 &lt;= queries[i][1] &lt; A.length</code></li></ol>



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



<p>Time complexity: O(n + |Q|)<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, Running time: 100 ms / 6.5 MB
class Solution {
public:
  vector&lt;int&gt; sumEvenAfterQueries(vector&lt;int&gt;&amp; A, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    int sum = 0;
    for (int i = 0; i &lt; A.size(); ++i)
      if (A[i] % 2 == 0)
        sum += A[i];
    vector&lt;int&gt; ans;
    for (const auto&amp; query : queries) {
      int&amp; a = A[query[1]];
      if (a % 2 == 0)
        sum -= a;
      a += query[0];
      if (a % 2 == 0)
        sum += a;
      ans.push_back(sum);
    }
    return ans;
  }
};</pre>

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

<pre class="urvanov-syntax-highlighter-plain-tag"># Author: Huahua, running time: 188 ms / 16.4MB
class Solution:
  def sumEvenAfterQueries(self, A: 'List[int]', queries: 'List[List[int]]') -&gt; 'List[int]':
    s = sum(x for x in A if x % 2 == 0)
    ans = []
    for val, index in queries:
      if A[index] % 2 == 0: s -= A[index]
      A[index] += val
      if A[index] % 2 == 0: s += A[index]
      ans.append(s)
    return ans</pre>
</div></div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/simulation/leetcode-985-sum-of-even-numbers-after-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 404. Sum of Left Leaves</title>
		<link>https://zxi.mytechroad.com/blog/tree/leetcode-404-sum-of-left-leaves/</link>
					<comments>https://zxi.mytechroad.com/blog/tree/leetcode-404-sum-of-left-leaves/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 16 Aug 2018 15:27:09 +0000</pubDate>
				<category><![CDATA[Tree]]></category>
		<category><![CDATA[sum]]></category>
		<category><![CDATA[tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3539</guid>

					<description><![CDATA[Solution: Recursion Time complexity: O(n) Space complexity: O(h) C++ [crayon-69a71f19e1a3b857713444/] Iterative [crayon-69a71f19e1a55775396229/] &#160;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 404. Sum of Left Leaves - 刷题找工作 EP5" width="500" height="281" src="https://www.youtube.com/embed/-79mkmH2lZs?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></p>
<h1><strong>Solution: Recursion</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(h)</p>
<p>C++</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int sumOfLeftLeaves(TreeNode* root) {
    if (!root) return 0;
    if (root-&gt;left &amp;&amp; !root-&gt;left-&gt;left &amp;&amp; !root-&gt;left-&gt;right)
        return root-&gt;left-&gt;val + sumOfLeftLeaves(root-&gt;right);
    return sumOfLeftLeaves(root-&gt;left) + sumOfLeftLeaves(root-&gt;right);
  }
};</pre><p>Iterative</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 4 ms
class Solution {
public:
  int sumOfLeftLeaves(TreeNode* root) {
    if (!root) return 0;
    queue&lt;TreeNode*&gt; q;
    q.push(root);
    int sum = 0;
    while (!q.empty()) {
      TreeNode* n = q.front();            
      q.pop();

      TreeNode* l = n-&gt;left;
      if (l) {
        if (!l-&gt;left &amp;&amp; !l-&gt;right)
            sum += l-&gt;val;
        else
            q.push(l);
      }
      if (n-&gt;right) q.push(n-&gt;right);
    }
    return sum;
  }
};</pre><p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/tree/leetcode-404-sum-of-left-leaves/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 643. Maximum Average Subarray I</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-643-maximum-average-subarray-i/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-643-maximum-average-subarray-i/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 16 Jul 2018 14:25:48 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[average]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[sliding window]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3183</guid>

					<description><![CDATA[Problem 题目大意：找出k长度的子数组的平均值的最大值。 https://leetcode.com/problems/maximum-average-subarray-i/description/ Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output&#8230;]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>题目大意：找出k长度的子数组的平均值的最大值。</p>
<p><a href="https://leetcode.com/problems/maximum-average-subarray-i/description/">https://leetcode.com/problems/maximum-average-subarray-i/description/</a></p>
<p>Given an array consisting of <code>n</code> integers, find the contiguous subarray of given length <code>k</code> that has the maximum average value. And you need to output the maximum average value.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [1,12,-5,-6,50,3], k = 4
<b>Output:</b> 12.75
<b>Explanation:</b> Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
</pre>
<p><b>Note:</b></p>
<ol>
<li>1 &lt;= <code>k</code> &lt;= <code>n</code> &lt;= 30,000.</li>
<li>Elements of the given array will be in the range [-10,000, 10,000].</li>
</ol>
<h1><strong>Solution: Sliding Window</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(1)</p>
<p>C++</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 124 ms
class Solution {
public:
  double findMaxAverage(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    int sum = 0;
    int ans = INT_MIN;
    for (int i = 0; i &lt; n; ++i) {
      if (i &gt;= k) sum -= nums[i - k];
      sum += nums[i];      
      if (i + 1 &gt;= k) ans = max(ans, sum);      
    }
    return static_cast&lt;double&gt;(ans) / k;
  }
};</pre><p></p>
<h1><strong>Related </strong><b>Problems</b></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/heap/leetcode-239-sliding-window-maximum/">花花酱 LeetCode 239. Sliding Window Maximum</a></li>
<li><a href="http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-813-largest-sum-of-averages/">花花酱 LeetCode 813. Largest Sum of Averages</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-643-maximum-average-subarray-i/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 523. Continuous Subarray Sum</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-523-continuous-subarray-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-523-continuous-subarray-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Jul 2018 14:59:05 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[k]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[reminder]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3127</guid>

					<description><![CDATA[Problem Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2&#8230;]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<p>Given a list of <b>non-negative</b> numbers and a target <b>integer</b> k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of <b>k</b>, that is, sums up to n*k where n is also an <b>integer</b>.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> [23, 2, 4, 6, 7],  k=6
<b>Output:</b> True
<b>Explanation:</b> Because [2, 4] is a continuous subarray of size 2 and sums up to 6.
</pre>
<p><b>Example 2:</b></p>
<pre class="crayon:false"><b>Input:</b> [23, 2, 6, 4, 7],  k=6
<b>Output:</b> True
<b>Explanation:</b> Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.
</pre>
<p><b>Note:</b></p>
<ol>
<li>The length of the array won&#8217;t exceed 10,000.</li>
<li>You may assume the sum of all the numbers is in the range of a signed 32-bit integer.</li>
</ol>
<h1><strong>Special case: </strong></h1>
<p>nums = [0,0], k = 0, return = True</p>
<h1><strong>Solution: Prefix Sum Reminder</strong></h1>
<p>Time complexity: O(n)</p>
<p>Space complexity: O(min(n, k))</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 16 ms (&lt;99.62%)
class Solution {
public:
  bool checkSubarraySum(vector&lt;int&gt;&amp; nums, int k) {    
    unordered_map&lt;int, int&gt; m; // sum % k -&gt; first index
    m[0] = -1;
    int sum = 0;
    for (int i = 0; i &lt; nums.size(); ++i) {
      sum += nums[i];
      if (k != 0) sum %= k;      
      if (m.count(sum)) {
        if (i - m.at(sum) &gt; 1) return true;
      } else {
        m[sum] = i;
      }
    }
    return false;
  }
};</pre><p></p>
<h1><strong>Related Problems</strong></h1>
<ul>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-560-subarray-sum-equals-k/">花花酱 LeetCode 560. Subarray Sum Equals K</a></li>
<li><a href="http://zxi.mytechroad.com/blog/hashtable/leetcode-525-contiguous-array/">花花酱 LeetCode 525. Contiguous Array</a></li>
</ul>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/hashtable/leetcode-523-continuous-subarray-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 698. Partition to K Equal Sum Subsets</title>
		<link>https://zxi.mytechroad.com/blog/searching/leetcode-698-partition-to-k-equal-sum-subsets/</link>
					<comments>https://zxi.mytechroad.com/blog/searching/leetcode-698-partition-to-k-equal-sum-subsets/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 14 Jul 2018 02:17:52 +0000</pubDate>
				<category><![CDATA[Search]]></category>
		<category><![CDATA[DFS]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[search]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=3119</guid>

					<description><![CDATA[Problem Given an array of integers nums and a positive integer k, find whether it&#8217;s possible to divide this array into knon-empty subsets whose sums are all equal. Example&#8230;]]></description>
										<content:encoded><![CDATA[<h1><strong>Problem</strong></h1>
<div class="question-description__3U1T">
<div>
<p>Given an array of integers <code>nums</code> and a positive integer <code>k</code>, find whether it&#8217;s possible to divide this array into <code>k</code>non-empty subsets whose sums are all equal.</p>
<p><b>Example 1:</b></p>
<pre class="crayon:false"><b>Input:</b> nums = [4, 3, 2, 3, 5, 2, 1], k = 4
<b>Output:</b> True
<b>Explanation:</b> It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equal sums.
</pre>
<p><b>Note:</b></p>
<ul>
<li><code>1 &lt;= k &lt;= len(nums) &lt;= 16</code>.</li>
<li><code>0 &lt; nums[i] &lt; 10000</code>.</li>
</ul>
<h1><strong>Solution: Search</strong></h1>
<p>Time complexity: O(n!)</p>
<p>Space complexity: O(n)</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 4 ms (&lt;99.21%)
class Solution {
public:
  bool canPartitionKSubsets(vector&lt;int&gt;&amp; nums, int k) {
    const int sum = accumulate(nums.begin(), nums.end(), 0);
    if (sum % k != 0) return false;    
    sort(nums.rbegin(), nums.rend());    
    return dfs(nums, sum / k, 0, k, 0);
  }
private:
  bool dfs(const vector&lt;int&gt;&amp; nums, int target, int cur, int k, int used) {
    if (k == 0) return used == (1 &lt;&lt; nums.size()) - 1;
    for (int i = 0; i &lt; nums.size(); ++i) {
      if (used &amp; (1 &lt;&lt; i)) continue;
      int t = cur + nums[i];
      if (t &gt; target) break; // Important
      int new_used = used | (1 &lt;&lt; i);
      if (t == target &amp;&amp; dfs(nums, target, 0, k - 1, new_used)) return true; 
      else if (dfs(nums, target, t, k, new_used)) return true;
    }
    return false;
  }  
};</pre><p>&nbsp;</p>
</div>
</div>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/searching/leetcode-698-partition-to-k-equal-sum-subsets/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 410. Split Array Largest Sum</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-410-split-array-largest-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-410-split-array-largest-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 04 Jul 2018 04:49:04 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[groups]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[largest]]></category>
		<category><![CDATA[subarray]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=2986</guid>

					<description><![CDATA[Problem Given an array which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays. Write an algorithm to minimize&#8230;]]></description>
										<content:encoded><![CDATA[<p><iframe loading="lazy" title="花花酱 LeetCode 410. Split Array Largest Sum - 刷题找工作 EP203" width="500" height="375" src="https://www.youtube.com/embed/_k-Jb4b7b_0?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></p>
<h1><strong>Problem</strong></h1>
<p>Given an array which consists of non-negative integers and an integer <i>m</i>, you can split the array into <i>m</i> non-empty continuous subarrays. Write an algorithm to minimize the largest sum among these <i>m</i> subarrays.</p>
<p><b>Note:</b><br />
If <i>n</i> is the length of array, assume the following constraints are satisfied:</p>
<ul>
<li>1 ≤ <i>n</i> ≤ 1000</li>
<li>1 ≤ <i>m</i> ≤ min(50, <i>n</i>)</li>
</ul>
<p><b>Examples:</b></p>
<pre class="crayon:false">Input:
<b>nums</b> = [7,2,5,10,8]
<b>m</b> = 2

Output:
18

Explanation:
There are four ways to split <b>nums</b> into two subarrays.
The best way is to split it into <b>[7,2,5]</b> and <b>[10,8]</b>,
where the largest sum among the two subarrays is only 18.
</pre>
<h1> <img loading="lazy" decoding="async" class="alignnone size-full wp-image-2997" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-1-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></h1>
<h1><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2996" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-2-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></h1>
<h1><img loading="lazy" decoding="async" class="alignnone size-full wp-image-2999" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-3.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-3.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-3-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2018/07/410-ep203-3-768x432.png 768w" sizes="auto, (max-width: 960px) 100vw, 960px" /></h1>
<h1><strong>Solution: DP</strong></h1>
<p>Time complexity: O(n^2*m)</p>
<p>Space complexity: O(n*m)</p>
<p>C++ / Recursion + Memorization</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 111 ms
class Solution {
public:
  int splitArray(vector&lt;int&gt;&amp; nums, int m) {
    const int n = nums.size();
    sums_ = vector&lt;int&gt;(n);
    mem_ = vector&lt;vector&lt;int&gt;&gt;(n, vector&lt;int&gt;(m + 1, INT_MAX));
    sums_[0] = nums[0];
    for (int i = 1; i &lt; n; ++i)
      sums_[i] = sums_[i - 1] + nums[i];
    return splitArray(nums, n - 1, m);
  }
private:
  vector&lt;vector&lt;int&gt;&gt; mem_;
  vector&lt;int&gt; sums_;
  
  // min of largest sum of spliting nums[0] ~ nums[k] into m groups
  int splitArray(const vector&lt;int&gt;&amp; nums, int k, int m) {
    if (m == 1) return sums_[k];
    if (m &gt; k + 1) return INT_MAX;    
    if (mem_[k][m] != INT_MAX) return mem_[k][m];
    int ans = INT_MAX;
    for (int i = 0; i &lt; k; ++i)
      ans = min(ans, max(splitArray(nums, i, m - 1), sums_[k] - sums_[i]));    
    return mem_[k][m] = ans;
  }
};</pre><p>C++ / DP</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 90 ms
class Solution {
public:
  int splitArray(vector&lt;int&gt;&amp; nums, int m) {
    const int n = nums.size();
    vector&lt;int&gt; sums(n);
    // dp[i][j] := min of largest sum of splitting nums[0] ~ nums[j] into i groups.
    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n, INT_MAX));
    sums[0] = nums[0];
    for (int i = 1; i &lt; n; ++i)
      sums[i] = sums[i - 1] + nums[i];
    for (int i = 0; i &lt; n; ++i)
      dp[1][i] = sums[i];
    
    for (int i = 2; i &lt;= m; ++i)
      for (int j = i - 1; j &lt; n; ++j)
        for (int k = 0; k &lt; j; ++k)
          dp[i][j] = min(dp[i][j], max(dp[i - 1][k], sums[j] - sums[k]));
    return dp[m][n - 1];
  }  
};</pre><p></p>
<h1><strong>Solution: Binary Search</strong></h1>
<p>Time complexity: O(log(sum(nums))*n)</p>
<p>Space complexity: O(1)</p><pre class="urvanov-syntax-highlighter-plain-tag">// Author: Huahua
// Running time: 3 ms
class Solution {
public:
  int splitArray(vector&lt;int&gt;&amp; nums, int m) {
    long l = *max_element(begin(nums), end(nums));
    long r = accumulate(begin(nums), end(nums), 0L) + 1;
    while (l &lt; r) {
      long limit = (r - l) / 2 + l;
      if (min_groups(nums, limit) &gt; m) 
        l = limit + 1;
      else
        r = limit;
    }
    return l;
  }
private:
  int min_groups(const vector&lt;int&gt;&amp; nums, long limit) {
    long sum = 0;
    int groups = 1;
    for (int num : nums) {
      if (sum + num &gt; limit) {
        sum = num;
        ++groups;
      } else {
        sum += num;
      }
    }    
    return groups;
  }
};</pre><p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-410-split-array-largest-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
