<?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>prefix sum Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/prefix-sum/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/prefix-sum/</link>
	<description></description>
	<lastBuildDate>Sat, 29 Apr 2023 15:31:24 +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>prefix sum Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/prefix-sum/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2640. Find the Score of All Prefixes of an Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2640-find-the-score-of-all-prefixes-of-an-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2640-find-the-score-of-all-prefixes-of-an-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 29 Apr 2023 15:30:47 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=10010</guid>

					<description><![CDATA[<p>We define the&#160;conversion array&#160;conver&#160;of an array&#160;arr&#160;as follows: conver[i] = arr[i] + max(arr[0..i])&#160;where&#160;max(arr[0..i])&#160;is the maximum value of&#160;arr[j]&#160;over&#160;0 &#60;= j &#60;= i. We also define the&#160;score&#160;of an&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2640-find-the-score-of-all-prefixes-of-an-array/">花花酱 LeetCode 2640. Find the Score of All Prefixes of an Array</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>We define the&nbsp;<strong>conversion array</strong>&nbsp;<code>conver</code>&nbsp;of an array&nbsp;<code>arr</code>&nbsp;as follows:</p>



<ul><li><code>conver[i] = arr[i] + max(arr[0..i])</code>&nbsp;where&nbsp;<code>max(arr[0..i])</code>&nbsp;is the maximum value of&nbsp;<code>arr[j]</code>&nbsp;over&nbsp;<code>0 &lt;= j &lt;= i</code>.</li></ul>



<p>We also define the&nbsp;<strong>score</strong>&nbsp;of an array&nbsp;<code>arr</code>&nbsp;as the sum of the values of the conversion array of&nbsp;<code>arr</code>.</p>



<p>Given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>, return&nbsp;<em>an array&nbsp;</em><code>ans</code><em>&nbsp;of length&nbsp;</em><code>n</code><em>&nbsp;where&nbsp;</em><code>ans[i]</code><em>&nbsp;is the score of the prefix</em>&nbsp;<code>nums[0..i]</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,7,5,10]
<strong>Output:</strong> [4,10,24,36,56]
<strong>Explanation:</strong> 
For the prefix [2], the conversion array is [4] hence the score is 4
For the prefix [2, 3], the conversion array is [4, 6] hence the score is 10
For the prefix [2, 3, 7], the conversion array is [4, 6, 14] hence the score is 24
For the prefix [2, 3, 7, 5], the conversion array is [4, 6, 14, 12] hence the score is 36
For the prefix [2, 3, 7, 5, 10], the conversion array is [4, 6, 14, 12, 20] hence the score is 56
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,2,4,8,16]
<strong>Output:</strong> [2,4,8,16,32,64]
<strong>Explanation:</strong> 
For the prefix [1], the conversion array is [2] hence the score is 2
For the prefix [1, 1], the conversion array is [2, 2] hence the score is 4
For the prefix [1, 1, 2], the conversion array is [2, 2, 4] hence the score is 8
For the prefix [1, 1, 2, 4], the conversion array is [2, 2, 4, 8] hence the score is 16
For the prefix [1, 1, 2, 4, 8], the conversion array is [2, 2, 4, 8, 16] hence the score is 32
For the prefix [1, 1, 2, 4, 8, 16], the conversion array is [2, 2, 4, 8, 16, 32] hence the score is 64
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<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:
  vector&lt;long long&gt; findPrefixScore(vector&lt;int&gt;&amp; nums) {
    vector&lt;long long&gt; ans(nums.size());
    for (int i = 0, m = 0; i &lt; nums.size(); ++i) {
      m = max(m, nums[i]);
      ans[i] = (i ? ans[i - 1] : 0) + nums[i] + m;
    }    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2640-find-the-score-of-all-prefixes-of-an-array/">花花酱 LeetCode 2640. Find the Score of All Prefixes of an Array</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/algorithms/array/leetcode-2640-find-the-score-of-all-prefixes-of-an-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2587. Rearrange Array to Maximize Prefix Score</title>
		<link>https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/</link>
					<comments>https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 12 Mar 2023 04:50:58 +0000</pubDate>
				<category><![CDATA[Greedy]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[greedy]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9981</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums. You can rearrange the elements of&#160;nums&#160;to&#160;any order&#160;(including the given order). Let&#160;prefix&#160;be the array containing the prefix sums of&#160;nums&#160;after rearranging it.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/">花花酱 LeetCode 2587. Rearrange Array to Maximize Prefix Score</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>. You can rearrange the elements of&nbsp;<code>nums</code>&nbsp;to&nbsp;<strong>any order</strong>&nbsp;(including the given order).</p>



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



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



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



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



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



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



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



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



<h2><strong>Solution: Greedy</strong></h2>



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



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int maxScore(vector&lt;int&gt;&amp; nums) {
    sort(rbegin(nums), rend(nums));
    int ans = 0;
    for (long i = 0, s = 0; i &lt; nums.size(); ++i) {
      s += nums[i];
      if (s &lt;= 0) break;
      ++ans;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/">花花酱 LeetCode 2587. Rearrange Array to Maximize Prefix Score</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/greedy/leetcode-2587-rearrange-array-to-maximize-prefix-score/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2574. Left and Right Sum Differences</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2574-left-and-right-sum-differences/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2574-left-and-right-sum-differences/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Feb 2023 05:54:12 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9964</guid>

					<description><![CDATA[<p>Given a&#160;0-indexed&#160;integer array&#160;nums, find a&#160;0-indexed&#160;integer array&#160;answer&#160;where: answer.length == nums.length. answer[i] = &#124;leftSum[i] - rightSum[i]&#124;. Where: leftSum[i]&#160;is the sum of elements to the left of the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2574-left-and-right-sum-differences/">花花酱 LeetCode 2574. Left and Right Sum Differences</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 a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>, find a&nbsp;<strong>0-indexed&nbsp;</strong>integer array&nbsp;<code>answer</code>&nbsp;where:</p>



<ul><li><code>answer.length == nums.length</code>.</li><li><code>answer[i] = |leftSum[i] - rightSum[i]|</code>.</li></ul>



<p>Where:</p>



<ul><li><code>leftSum[i]</code>&nbsp;is the sum of elements to the left of the index&nbsp;<code>i</code>&nbsp;in the array&nbsp;<code>nums</code>. If there is no such element,&nbsp;<code>leftSum[i] = 0</code>.</li><li><code>rightSum[i]</code>&nbsp;is the sum of elements to the right of the index&nbsp;<code>i</code>&nbsp;in the array&nbsp;<code>nums</code>. If there is no such element,&nbsp;<code>rightSum[i] = 0</code>.</li></ul>



<p>Return&nbsp;<em>the array</em>&nbsp;<code>answer</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,4,8,3]
<strong>Output:</strong> [15,1,11,22]
<strong>Explanation:</strong> The array leftSum is [0,10,14,22] and the array rightSum is [15,11,3,0].
The array answer is [|0 - 15|,|10 - 11|,|14 - 3|,|22 - 0|] = [15,1,11,22].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1]
<strong>Output:</strong> [0]
<strong>Explanation:</strong> The array leftSum is [0] and the array rightSum is [0].
The array answer is [|0 - 0|] = [0].
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 1000</code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<p><strong>Solution: O(1) Space</strong></p>



<p>Pre-compute the sum of all numbers as right sum, and accumulate left sum on the fly then we can achieve O(1) space.</p>



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



<p></p>



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; leftRigthDifference(vector&lt;int&gt;&amp; nums) {
    int right = accumulate(begin(nums), end(nums), 0);
    vector&lt;int&gt; ans;
    for (int i = 0, left = 0; i &lt; nums.size(); ++i) {
      right -= nums[i];
      ans.push_back(abs(left - right));
      left += nums[i];      
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2574-left-and-right-sum-differences/">花花酱 LeetCode 2574. Left and Right Sum Differences</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/algorithms/array/leetcode-2574-left-and-right-sum-differences/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2559. Count Vowel Strings in Ranges</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2559-count-vowel-strings-in-ranges/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2559-count-vowel-strings-in-ranges/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 05 Feb 2023 05:25:04 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[vowel]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9929</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;array of strings&#160;words&#160;and a 2D array of integers&#160;queries. Each query&#160;queries[i] = [li, ri]&#160;asks us to find the number of strings present in&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2559-count-vowel-strings-in-ranges/">花花酱 LeetCode 2559. Count Vowel Strings in Ranges</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array of strings&nbsp;<code>words</code>&nbsp;and a 2D array of integers&nbsp;<code>queries</code>.</p>



<p>Each query&nbsp;<code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>&nbsp;asks us to find the number of strings present in the range&nbsp;<code>l<sub>i</sub></code>&nbsp;to&nbsp;<code>r<sub>i</sub></code>&nbsp;(both&nbsp;<strong>inclusive</strong>) of&nbsp;<code>words</code>&nbsp;that start and end with a vowel.</p>



<p>Return an array&nbsp;<code>ans</code>&nbsp;of size&nbsp;<code>queries.length</code>, where&nbsp;<code>ans[i]</code>&nbsp;is the answer to the&nbsp;<code>i</code><sup>th</sup>&nbsp;query.</p>



<p><strong>Note</strong>&nbsp;that the vowel letters are&nbsp;<code>'a'</code>,&nbsp;<code>'e'</code>,&nbsp;<code>'i'</code>,&nbsp;<code>'o'</code>, and&nbsp;<code>'u'</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["aba","bcb","ece","aa","e"], queries = [[0,2],[1,4],[1,1]]
<strong>Output:</strong> [2,3,0]
<strong>Explanation:</strong> The strings starting and ending with a vowel are "aba", "ece", "aa" and "e".
The answer to the query [0,2] is 2 (strings "aba" and "ece").
to query [1,4] is 3 (strings "ece", "aa", "e").
to query [1,1] is 0.
We return [2,3,0].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> words = ["a","e","i"], queries = [[0,2],[0,1],[2,2]]
<strong>Output:</strong> [3,2,1]
<strong>Explanation:</strong> Every string satisfies the conditions, so we return [3,2,1].</pre>



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



<ul><li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= words[i].length &lt;= 40</code></li><li><code>words[i]</code>&nbsp;consists only of lowercase English letters.</li><li><code>sum(words[i].length) &lt;= 3 * 10<sup>5</sup></code></li><li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li><li><code>0 &lt;= l<sub>i</sub> &lt;= r<sub>i</sub> &lt;&nbsp;words.length</code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<p>Let sum[i] := number of valid strings in words[0:i]</p>



<p>For each query [l, r], answer will be sum[r + 1] &#8211; sum[l]</p>



<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="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  vector&lt;int&gt; vowelStrings(vector&lt;string&gt;&amp; words, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    const size_t n = words.size();
    vector&lt;int&gt; sum(n + 1);
    auto check = [](char c) {
      return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
    };
    for (size_t i = 0; i &lt; n; ++i)
      sum[i + 1] = sum[i] + 
        (check(words[i][0]) &amp;&amp; check(words[i][words[i].size() - 1]));
    vector&lt;int&gt; ans;
    for (const auto&amp; q : queries)
      ans.push_back(sum[q[1] + 1] - sum[q[0]]);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2559-count-vowel-strings-in-ranges/">花花酱 LeetCode 2559. Count Vowel Strings in Ranges</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/algorithms/array/leetcode-2559-count-vowel-strings-in-ranges/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2420. Find All Good Indices</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2420-find-all-good-indices/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2420-find-all-good-indices/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 26 Sep 2022 17:18:29 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[precompute]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9850</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;of size&#160;n&#160;and a positive integer&#160;k. We call an index&#160;i&#160;in the range&#160;k &#60;= i &#60; n - k&#160;good&#160;if the following conditions are&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2420-find-all-good-indices/">花花酱 LeetCode 2420. Find All Good Indices</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of size&nbsp;<code>n</code>&nbsp;and a positive integer&nbsp;<code>k</code>.</p>



<p>We call an index&nbsp;<code>i</code>&nbsp;in the range&nbsp;<code>k &lt;= i &lt; n - k</code>&nbsp;<strong>good</strong>&nbsp;if the following conditions are satisfied:</p>



<ul><li>The&nbsp;<code>k</code>&nbsp;elements that are just&nbsp;<strong>before</strong>&nbsp;the index&nbsp;<code>i</code>&nbsp;are in&nbsp;<strong>non-increasing</strong>&nbsp;order.</li><li>The&nbsp;<code>k</code>&nbsp;elements that are just&nbsp;<strong>after</strong>&nbsp;the index&nbsp;<code>i</code>&nbsp;are in&nbsp;<strong>non-decreasing</strong>&nbsp;order.</li></ul>



<p>Return&nbsp;<em>an array of all good indices sorted in&nbsp;<strong>increasing</strong>&nbsp;order</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,1,1,1,3,4,1], k = 2
<strong>Output:</strong> [2,3]
<strong>Explanation:</strong> There are two good indices in the array:
- Index 2. The subarray [2,1] is in non-increasing order, and the subarray [1,3] is in non-decreasing order.
- Index 3. The subarray [1,1] is in non-increasing order, and the subarray [3,4] is in non-decreasing order.
Note that the index 4 is not good because [4,1] is not non-decreasing.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,1,1,2], k = 2
<strong>Output:</strong> []
<strong>Explanation:</strong> There are no good indices in this array.
</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>3 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li><li><code>1 &lt;= k &lt;= n / 2</code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<p>Let before[i] = length of longest non-increasing subarray ends of nums[i].<br>Let after[i] = length of longest non-decreasing subarray ends of nums[i].</p>



<p>An index is good if nums[i &#8211; 1] &gt;= k and nums[i + k] &gt;= k</p>



<p>Time complexity: O(n + (n &#8211; 2*k))<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:
  vector&lt;int&gt; goodIndices(vector&lt;int&gt;&amp; nums, int k) {
    const int n = nums.size();
    vector&lt;int&gt; before(n, 1);
    vector&lt;int&gt; after(n, 1);
    for (int i = 1; i &lt; n; ++i) {
      if (nums[i] &lt;= nums[i - 1])
        before[i] = before[i - 1] + 1;      
      if (nums[i] &gt;= nums[i - 1])
        after[i] = after[i - 1] + 1;    
    }
    vector&lt;int&gt; ans;
    for (int i = k; i + k &lt; n; ++i) {
      if (before[i - 1] &gt;= k &amp;&amp; after[i + k] &gt;= k)
        ans.push_back(i);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2420-find-all-good-indices/">花花酱 LeetCode 2420. Find All Good Indices</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-2420-find-all-good-indices/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2270. Number of Ways to Split Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2270-number-of-ways-to-split-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2270-number-of-ways-to-split-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 May 2022 19:09:06 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9744</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;integer array&#160;nums&#160;of length&#160;n. nums&#160;contains a&#160;valid split&#160;at index&#160;i&#160;if the following are true: The sum of the first&#160;i + 1&#160;elements is&#160;greater than or equal&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2270-number-of-ways-to-split-array/">花花酱 LeetCode 2270. Number of Ways to Split Array</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;integer array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>.</p>



<p><code>nums</code>&nbsp;contains a&nbsp;<strong>valid split</strong>&nbsp;at index&nbsp;<code>i</code>&nbsp;if the following are true:</p>



<ul><li>The sum of the first&nbsp;<code>i + 1</code>&nbsp;elements is&nbsp;<strong>greater than or equal to</strong>&nbsp;the sum of the last&nbsp;<code>n - i - 1</code>&nbsp;elements.</li><li>There is&nbsp;<strong>at least one</strong>&nbsp;element to the right of&nbsp;<code>i</code>. That is,&nbsp;<code>0 &lt;= i &lt; n - 1</code>.</li></ul>



<p>Return&nbsp;<em>the number of&nbsp;<strong>valid splits</strong>&nbsp;in</em>&nbsp;<code>nums</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,4,-8,7]
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
There are three ways of splitting nums into two non-empty parts:
- Split nums at index 0. Then, the first part is [10], and its sum is 10. The second part is [4,-8,7], and its sum is 3. Since 10 &gt;= 3, i = 0 is a valid split.
- Split nums at index 1. Then, the first part is [10,4], and its sum is 14. The second part is [-8,7], and its sum is -1. Since 14 &gt;= -1, i = 1 is a valid split.
- Split nums at index 2. Then, the first part is [10,4,-8], and its sum is 6. The second part is [7], and its sum is 7. Since 6 &lt; 7, i = 2 is not a valid split.
Thus, the number of valid splits in nums is 2.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,1,0]
<strong>Output:</strong> 2
<strong>Explanation:</strong> 
There are two valid splits in nums:
- Split nums at index 1. Then, the first part is [2,3], and its sum is 5. The second part is [1,0], and its sum is 1. Since 5 &gt;= 1, i = 1 is a valid split. 
- Split nums at index 2. Then, the first part is [2,3,1], and its sum is 6. The second part is [0], and its sum is 0. Since 6 &gt;= 0, i = 2 is a valid split.
</pre>



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



<ul><li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>-10<sup>5</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Prefix/Suffix Sum</strong></h2>



<p>Note: sum can be greater than 2^31, use long!</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 waysToSplitArray(vector&lt;int&gt;&amp; A) {    
    int ans = 0;
    for (long i = 0, l = 0, r = accumulate(begin(A), end(A), 0l); i &lt; A.size() - 1; ++i)       
      ans += (l += A[i]) &gt;= (r -= A[i]);
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2270-number-of-ways-to-split-array/">花花酱 LeetCode 2270. Number of Ways to Split Array</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/algorithms/array/leetcode-2270-number-of-ways-to-split-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2155. All Divisions With the Highest Score of a Binary Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2155-all-divisions-with-the-highest-score-of-a-binary-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2155-all-divisions-with-the-highest-score-of-a-binary-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 05 Feb 2022 06:00:35 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[divide]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[precompute]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9484</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;binary array&#160;nums&#160;of length&#160;n.&#160;nums&#160;can be divided at index&#160;i&#160;(where&#160;0 &#60;= i &#60;= n)&#160;into two arrays (possibly empty)&#160;numsleft&#160;and&#160;numsright: numsleft&#160;has all the elements of&#160;nums&#160;between index&#160;0&#160;and&#160;i -&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2155-all-divisions-with-the-highest-score-of-a-binary-array/">花花酱 LeetCode 2155. All Divisions With the Highest Score of a Binary Array</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;binary array&nbsp;<code>nums</code>&nbsp;of length&nbsp;<code>n</code>.&nbsp;<code>nums</code>&nbsp;can be divided at index&nbsp;<code>i</code>&nbsp;(where&nbsp;<code>0 &lt;= i &lt;= n)</code>&nbsp;into two arrays (possibly empty)&nbsp;<code>nums<sub>left</sub></code>&nbsp;and&nbsp;<code>nums<sub>right</sub></code>:</p>



<ul><li><code>nums<sub>left</sub></code>&nbsp;has all the elements of&nbsp;<code>nums</code>&nbsp;between index&nbsp;<code>0</code>&nbsp;and&nbsp;<code>i - 1</code>&nbsp;<strong>(inclusive)</strong>, while&nbsp;<code>nums<sub>right</sub></code>&nbsp;has all the elements of nums between index&nbsp;<code>i</code>&nbsp;and&nbsp;<code>n - 1</code>&nbsp;<strong>(inclusive)</strong>.</li><li>If&nbsp;<code>i == 0</code>,&nbsp;<code>nums<sub>left</sub></code>&nbsp;is&nbsp;<strong>empty</strong>, while&nbsp;<code>nums<sub>right</sub></code>&nbsp;has all the elements of&nbsp;<code>nums</code>.</li><li>If&nbsp;<code>i == n</code>,&nbsp;<code>nums<sub>left</sub></code>&nbsp;has all the elements of nums, while&nbsp;<code>nums<sub>right</sub></code>&nbsp;is&nbsp;<strong>empty</strong>.</li></ul>



<p>The&nbsp;<strong>division score</strong>&nbsp;of an index&nbsp;<code>i</code>&nbsp;is the&nbsp;<strong>sum</strong>&nbsp;of the number of&nbsp;<code>0</code>&#8216;s in&nbsp;<code>nums<sub>left</sub></code>&nbsp;and the number of&nbsp;<code>1</code>&#8216;s in&nbsp;<code>nums<sub>right</sub></code>.</p>



<p>Return&nbsp;<em><strong>all distinct indices</strong>&nbsp;that have the&nbsp;<strong>highest</strong>&nbsp;possible&nbsp;<strong>division score</strong></em>. You may return the answer in&nbsp;<strong>any order</strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,0,1,0]
<strong>Output:</strong> [2,4]
<strong>Explanation:</strong> Division at index
- 0: nums<sub>left</sub> is []. nums<sub>right</sub> is [0,0,<strong>1</strong>,0]. The score is 0 + 1 = 1.
- 1: nums<sub>left</sub> is [<strong>0</strong>]. nums<sub>right</sub> is [0,<strong>1</strong>,0]. The score is 1 + 1 = 2.
- 2: nums<sub>left</sub> is [<strong>0</strong>,<strong>0</strong>]. nums<sub>right</sub> is [<strong>1</strong>,0]. The score is 2 + 1 = 3.
- 3: nums<sub>left</sub> is [<strong>0</strong>,<strong>0</strong>,1]. nums<sub>right</sub> is [0]. The score is 2 + 0 = 2.
- 4: nums<sub>left</sub> is [<strong>0</strong>,<strong>0</strong>,1,<strong>0</strong>]. nums<sub>right</sub> is []. The score is 3 + 0 = 3.
Indices 2 and 4 both have the highest possible division score 3.
Note the answer [4,2] would also be accepted.</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [0,0,0]
<strong>Output:</strong> [3]
<strong>Explanation:</strong> Division at index
- 0: nums<sub>left</sub> is []. nums<sub>right</sub> is [0,0,0]. The score is 0 + 0 = 0.
- 1: nums<sub>left</sub> is [<strong>0</strong>]. nums<sub>right</sub> is [0,0]. The score is 1 + 0 = 1.
- 2: nums<sub>left</sub> is [<strong>0</strong>,<strong>0</strong>]. nums<sub>right</sub> is [0]. The score is 2 + 0 = 2.
- 3: nums<sub>left</sub> is [<strong>0</strong>,<strong>0</strong>,<strong>0</strong>]. nums<sub>right</sub> is []. The score is 3 + 0 = 3.
Only index 3 has the highest possible division score 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1]
<strong>Output:</strong> [0]
<strong>Explanation:</strong> Division at index
- 0: nums<sub>left</sub> is []. nums<sub>right</sub> is [<strong>1</strong>,<strong>1</strong>]. The score is 0 + 2 = 2.
- 1: nums<sub>left</sub> is [1]. nums<sub>right</sub> is [<strong>1</strong>]. The score is 0 + 1 = 1.
- 2: nums<sub>left</sub> is [1,1]. nums<sub>right</sub> is []. The score is 0 + 0 = 0.
Only index 0 has the highest possible division score 2.
</pre>



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



<ul><li><code>n == nums.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>nums[i]</code>&nbsp;is either&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li></ul>



<h2><strong>Solution: Precompute + Prefix Sum</strong></h2>



<p>Count how many ones in the array, track the prefix sum to compute score for each index in O(1).</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:
  vector&lt;int&gt; maxScoreIndices(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    const int t = accumulate(begin(nums), end(nums), 0);    
    vector&lt;int&gt; ans;
    for (int i = 0, p = 0, b = 0; i &lt;= n; ++i) {
      const int s = (i - p) + (t - p);      
      if (s &gt; b) {
        b = s; ans.clear();
      }
      if (s == b) ans.push_back(i);
      if (i != n) p += nums[i];
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2155-all-divisions-with-the-highest-score-of-a-binary-array/">花花酱 LeetCode 2155. All Divisions With the Highest Score of a Binary Array</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/algorithms/array/leetcode-2155-all-divisions-with-the-highest-score-of-a-binary-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2121. Intervals Between Identical Elements</title>
		<link>https://zxi.mytechroad.com/blog/hashtable/leetcode-2121-intervals-between-identical-elements/</link>
					<comments>https://zxi.mytechroad.com/blog/hashtable/leetcode-2121-intervals-between-identical-elements/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 26 Dec 2021 13:34:56 +0000</pubDate>
				<category><![CDATA[Hashtable]]></category>
		<category><![CDATA[hash table]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9253</guid>

					<description><![CDATA[<p>You are given a&#160;0-indexed&#160;array of&#160;n&#160;integers&#160;arr. The&#160;interval&#160;between two elements in&#160;arr&#160;is defined as the&#160;absolute difference&#160;between their indices. More formally, the&#160;interval&#160;between&#160;arr[i]&#160;and&#160;arr[j]&#160;is&#160;&#124;i - j&#124;. Return&#160;an array&#160;intervals&#160;of length&#160;n&#160;where&#160;intervals[i]&#160;is&#160;the sum of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2121-intervals-between-identical-elements/">花花酱 LeetCode 2121. Intervals Between Identical Elements</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>You are given a&nbsp;<strong>0-indexed</strong>&nbsp;array of&nbsp;<code>n</code>&nbsp;integers&nbsp;<code>arr</code>.</p>



<p>The&nbsp;<strong>interval</strong>&nbsp;between two elements in&nbsp;<code>arr</code>&nbsp;is defined as the&nbsp;<strong>absolute difference</strong>&nbsp;between their indices. More formally, the&nbsp;<strong>interval</strong>&nbsp;between&nbsp;<code>arr[i]</code>&nbsp;and&nbsp;<code>arr[j]</code>&nbsp;is&nbsp;<code>|i - j|</code>.</p>



<p>Return&nbsp;<em>an array</em>&nbsp;<code>intervals</code>&nbsp;<em>of length</em>&nbsp;<code>n</code>&nbsp;<em>where</em>&nbsp;<code>intervals[i]</code>&nbsp;<em>is&nbsp;<strong>the sum of intervals</strong>&nbsp;between&nbsp;</em><code>arr[i]</code><em>&nbsp;and each element in&nbsp;</em><code>arr</code><em>&nbsp;with the same value as&nbsp;</em><code>arr[i]</code><em>.</em></p>



<p><strong>Note:</strong>&nbsp;<code>|x|</code>&nbsp;is the absolute value of&nbsp;<code>x</code>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [2,1,3,1,2,3,3]
<strong>Output:</strong> [4,2,7,2,4,4,5]
<strong>Explanation:</strong>
- Index 0: Another 2 is found at index 4. |0 - 4| = 4
- Index 1: Another 1 is found at index 3. |1 - 3| = 2
- Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7
- Index 3: Another 1 is found at index 1. |3 - 1| = 2
- Index 4: Another 2 is found at index 0. |4 - 0| = 4
- Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4
- Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> arr = [10,5,10,10]
<strong>Output:</strong> [5,0,3,4]
<strong>Explanation:</strong>
- Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5
- Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.
- Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3
- Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
</pre>



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



<ul><li><code>n == arr.length</code></li><li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= arr[i] &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: Math / Hashtable + Prefix Sum </strong></h2>



<p>For each arr[i], suppose it occurs in the array of total c times, among which k of them are in front of it and c &#8211; k &#8211; 1 of them are after it. Then the total sum intervals:<br>(i &#8211; j<sub>1</sub>) + (i &#8211; j<sub>2</sub>) + &#8230; + (i &#8211; j<sub>k</sub>) + (j<sub>k+1</sub>-i) + (j<sub>k+2</sub>-i) + &#8230; + (j<sub>c</sub>-i)<br>&lt;=&gt; k * i &#8211; sum(j<sub>1</sub>~j<sub>k</sub>)  + sum(j<sub>k+1</sub>~j<sub>c</sub>) &#8211; (c &#8211; k &#8211; 1) * i</p>



<p>Use a hashtable to store the indies of each unique number in the array and compute the prefix sum for fast range sum query.</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:
  vector&lt;long long&gt; getDistances(vector&lt;int&gt;&amp; arr) {
    const int n = arr.size();
    unordered_map&lt;int, vector&lt;long long&gt;&gt; m;
    vector&lt;int&gt; pos(n);
    for (int i = 0; i &lt; n; ++i) {
      m[arr[i]].push_back(i);
      pos[i] = m[arr[i]].size() - 1;
    }
    for (auto&amp; [k, idx] : m)
      partial_sum(begin(idx), end(idx), begin(idx));      
    vector&lt;long long&gt; ans(n);
    for (int i = 0; i &lt; n; ++i) {
      const auto&amp; sums = m[arr[i]];
      const long long k = pos[i];
      const long long c = sums.size();      
      if (k &gt; 0) ans[i] += k * i - sums[k - 1];
      if (k + 1 &lt; c) ans[i] += (sums[c - 1] - sums[k]) - (c - k - 1) * i;
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/hashtable/leetcode-2121-intervals-between-identical-elements/">花花酱 LeetCode 2121. Intervals Between Identical Elements</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-2121-intervals-between-identical-elements/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1895. Largest Magic Square</title>
		<link>https://zxi.mytechroad.com/blog/geometry/leetcode-1895-largest-magic-square/</link>
					<comments>https://zxi.mytechroad.com/blog/geometry/leetcode-1895-largest-magic-square/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 10 Aug 2021 03:24:57 +0000</pubDate>
				<category><![CDATA[Geometry]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8555</guid>

					<description><![CDATA[<p>A&#160;k x k&#160;magic square&#160;is a&#160;k x k&#160;grid filled with integers such that every row sum, every column sum, and both diagonal sums are&#160;all equal. The&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1895-largest-magic-square/">花花酱 LeetCode 1895. Largest Magic Square</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;<code>k x k</code>&nbsp;<strong>magic square</strong>&nbsp;is a&nbsp;<code>k x k</code>&nbsp;grid filled with integers such that every row sum, every column sum, and both diagonal sums are&nbsp;<strong>all equal</strong>. The integers in the magic square&nbsp;<strong>do not have to be distinct</strong>. Every&nbsp;<code>1 x 1</code>&nbsp;grid is trivially a&nbsp;<strong>magic square</strong>.</p>



<p>Given an&nbsp;<code>m x n</code>&nbsp;integer&nbsp;<code>grid</code>, return&nbsp;<em>the&nbsp;<strong>size</strong>&nbsp;(i.e., the side length&nbsp;</em><code>k</code><em>) of the&nbsp;<strong>largest magic square</strong>&nbsp;that can be found within this grid</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/05/29/magicsquare-grid.jpg" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> grid = [[7,1,4,5,6],[2,5,1,6,4],[1,5,4,3,2],[1,2,7,3,4]]
<strong>Output:</strong> 3
<strong>Explanation:</strong> The largest magic square has a size of 3.
Every row sum, column sum, and diagonal sum of this magic square is equal to 12.
- Row sums: 5+1+6 = 5+4+3 = 2+7+3 = 12
- Column sums: 5+5+2 = 1+4+7 = 6+3+3 = 12
- Diagonal sums: 5+4+3 = 6+4+2 = 12
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/05/29/magicsquare2-grid.jpg" alt=""/></figure>



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



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



<ul><li><code>m == grid.length</code></li><li><code>n == grid[i].length</code></li><li><code>1 &lt;= m, n &lt;= 50</code></li><li><code>1 &lt;= grid[i][j] &lt;= 10<sup>6</sup></code></li></ul>



<h2><strong>Solution: Brute Force w/ Prefix Sum</strong></h2>



<p>Compute the prefix sum for each row and each column.</p>



<p>And check all possible squares.</p>



<p>Time complexity: O(m*n*min(m,n)<sup>2</sup>)<br>Space complexity: O(m*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 largestMagicSquare(vector&lt;vector&lt;int&gt;&gt;&amp; grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector&lt;vector&lt;int&gt;&gt; rows(m, vector&lt;int&gt;(n + 1));
    vector&lt;vector&lt;int&gt;&gt; cols(n, vector&lt;int&gt;(m + 1));
    for (int i = 0; i &lt; m; ++i)
      for (int j = 0; j &lt; n; ++j) {
        rows[i][j + 1] = rows[i][j] + grid[i][j];
        cols[j][i + 1] = cols[j][i] + grid[i][j];
      }
    for (int k = min(m, n); k &gt;= 2; --k)
      for (int i = 0; i + k &lt;= m; ++i)
        for (int j = 0; j + k &lt;= n; ++j) {
          vector&lt;int&gt; s;
          for (int r = 0; r &lt; k; ++r) 
            s.push_back(rows[i + r][j + k] - rows[i + r][j]);
          for (int c = 0; c &lt; k; ++c)
            s.push_back(cols[j + c][i + k] - cols[j + c][i]);
          int d1 = 0;
          int d2 = 0;
          for (int d = 0; d &lt; k; ++d) {
            d1 += grid[i + d][j + d];
            d2 += grid[i + d][j + k - d - 1];
          }
          s.push_back(d1);
          s.push_back(d2);          
          if (count(begin(s), end(s), s[0]) == s.size()) return k;
        }
    return 1;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/geometry/leetcode-1895-largest-magic-square/">花花酱 LeetCode 1895. Largest Magic Square</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/geometry/leetcode-1895-largest-magic-square/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1800. Maximum Ascending Subarray Sum</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1800-maximum-ascending-subarray-sum/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1800-maximum-ascending-subarray-sum/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 22 Mar 2021 05:23:26 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8263</guid>

					<description><![CDATA[<p>Given an array of positive integers&#160;nums, return the&#160;maximum possible sum of an&#160;ascending&#160;subarray in&#160;nums. A subarray is defined as a contiguous sequence of numbers in an&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1800-maximum-ascending-subarray-sum/">花花酱 LeetCode 1800. Maximum Ascending Subarray 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[
<p>Given an array of positive integers&nbsp;<code>nums</code>, return the&nbsp;<em>maximum possible sum of an&nbsp;<strong>ascending</strong>&nbsp;subarray in&nbsp;</em><code>nums</code>.</p>



<p>A subarray is defined as a contiguous sequence of numbers in an array.</p>



<p>A subarray&nbsp;<code>[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>]</code>&nbsp;is&nbsp;<strong>ascending</strong>&nbsp;if for all&nbsp;<code>i</code>&nbsp;where&nbsp;<code>l &lt;= i &lt; r</code>,&nbsp;<code>nums<sub>i&nbsp;</sub>&lt; nums<sub>i+1</sub></code>. Note that a subarray of size&nbsp;<code>1</code>&nbsp;is&nbsp;<strong>ascending</strong>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,20,30,5,10,50]
<strong>Output:</strong> 65
<strong>Explanation: </strong>[5,10,50] is the ascending subarray with the maximum sum of 65.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [10,20,30,40,50]
<strong>Output:</strong> 150
<strong>Explanation: </strong>[10,20,30,40,50] is the ascending subarray with the maximum sum of 150.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [12,17,15,13,10,11,12]
<strong>Output:</strong> 33
<strong>Explanation: </strong>[10,11,12] is the ascending subarray with the maximum sum of 33.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [100,10,1]
<strong>Output:</strong> 100
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 100</code></li><li><code>1 &lt;= nums[i] &lt;= 100</code></li></ul>



<h2><strong>Solution: Running sum with resetting</strong></h2>



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



<p>Track the running sum and reset it to zero if nums[i] &lt;= nums[i &#8211; 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 maxAscendingSum(vector&lt;int&gt;&amp; nums) {    
    int ans = 0;
    for (int i = 0, s = 0; i &lt; nums.size(); ++i) {
      if (i &amp;&amp; nums[i] &lt;= nums[i - 1])
        s = 0;
      ans = max(ans, s += nums[i]);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1800-maximum-ascending-subarray-sum/">花花酱 LeetCode 1800. Maximum Ascending Subarray 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/algorithms/array/leetcode-1800-maximum-ascending-subarray-sum/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1769-minimum-number-of-operations-to-move-all-balls-to-each-box/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1769-minimum-number-of-operations-to-move-all-balls-to-each-box/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 21 Feb 2021 07:07:32 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8146</guid>

					<description><![CDATA[<p>You have&#160;n&#160;boxes. You are given a binary string&#160;boxes&#160;of length&#160;n, where&#160;boxes[i]&#160;is&#160;'0'&#160;if the&#160;ith&#160;box is&#160;empty, and&#160;'1'&#160;if it contains&#160;one&#160;ball. In one operation, you can move&#160;one&#160;ball from a box to&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1769-minimum-number-of-operations-to-move-all-balls-to-each-box/">花花酱 LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box</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>You have&nbsp;<code>n</code>&nbsp;boxes. You are given a binary string&nbsp;<code>boxes</code>&nbsp;of length&nbsp;<code>n</code>, where&nbsp;<code>boxes[i]</code>&nbsp;is&nbsp;<code>'0'</code>&nbsp;if the&nbsp;<code>i<sup>th</sup></code>&nbsp;box is&nbsp;<strong>empty</strong>, and&nbsp;<code>'1'</code>&nbsp;if it contains&nbsp;<strong>one</strong>&nbsp;ball.</p>



<p>In one operation, you can move&nbsp;<strong>one</strong>&nbsp;ball from a box to an adjacent box. Box&nbsp;<code>i</code>&nbsp;is adjacent to box&nbsp;<code>j</code>&nbsp;if&nbsp;<code>abs(i - j) == 1</code>. Note that after doing so, there may be more than one ball in some boxes.</p>



<p>Return an array&nbsp;<code>answer</code>&nbsp;of size&nbsp;<code>n</code>, where&nbsp;<code>answer[i]</code>&nbsp;is the&nbsp;<strong>minimum</strong>&nbsp;number of operations needed to move all the balls to the&nbsp;<code>i<sup>th</sup></code>&nbsp;box.</p>



<p>Each&nbsp;<code>answer[i]</code>&nbsp;is calculated considering the&nbsp;<strong>initial</strong>&nbsp;state of the boxes.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = "110"
<strong>Output:</strong> [1,1,3]
<strong>Explanation:</strong> The answer for each box is as follows:
1) First box: you will have to move one ball from the second box to the first box in one operation.
2) Second box: you will have to move one ball from the first box to the second box in one operation.
3) Third box: you will have to move one ball from the first box to the third box in two operations, and move one ball from the second box to the third box in one operation.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> boxes = "001011"
<strong>Output:</strong> [11,8,5,4,3,4]</pre>



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



<ul><li><code>n == boxes.length</code></li><li><code>1 &lt;= n &lt;= 2000</code></li><li><code>boxes[i]</code>&nbsp;is either&nbsp;<code>'0'</code>&nbsp;or&nbsp;<code>'1'</code></li></ul>



<h2><strong>Solution: Prefix Sum + DP</strong></h2>



<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:
  vector&lt;int&gt; minOperations(string boxes) {
    const int n = boxes.size();
    vector&lt;int&gt; ans(n);    
    for (int i = 0, c = 0, s = 0; i &lt; n; ++i) {
      ans[i] += c;
      c += (s += boxes[i] - '0');
    }
    for (int i = n - 1, c = 0, s = 0; i &gt;= 0; --i) {
      ans[i] += c;
      c += (s += boxes[i] - '0');
    }    
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1769-minimum-number-of-operations-to-move-all-balls-to-each-box/">花花酱 LeetCode 1769. Minimum Number of Operations to Move All Balls to Each Box</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-1769-minimum-number-of-operations-to-move-all-balls-to-each-box/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sat, 06 Feb 2021 16:24:40 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[subarray]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8065</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums. The&#160;absolute sum&#160;of a subarray&#160;[numsl, numsl+1, ..., numsr-1, numsr]&#160;is&#160;abs(numsl&#160;+ numsl+1&#160;+ ... + numsr-1&#160;+ numsr). Return&#160;the&#160;maximum&#160;absolute sum of any&#160;(possibly empty)&#160;subarray of&#160;nums.&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/">花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</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>You are given an integer array&nbsp;<code>nums</code>. The&nbsp;<strong>absolute sum</strong>&nbsp;of a subarray&nbsp;<code>[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>]</code>&nbsp;is&nbsp;<code>abs(nums<sub>l</sub>&nbsp;+ nums<sub>l+1</sub>&nbsp;+ ... + nums<sub>r-1</sub>&nbsp;+ nums<sub>r</sub>)</code>.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>maximum</strong>&nbsp;absolute sum of any&nbsp;<strong>(possibly empty)</strong>&nbsp;subarray of&nbsp;</em><code>nums</code>.</p>



<p>Note that&nbsp;<code>abs(x)</code>&nbsp;is defined as follows:</p>



<ul><li>If&nbsp;<code>x</code>&nbsp;is a negative integer, then&nbsp;<code>abs(x) = -x</code>.</li><li>If&nbsp;<code>x</code>&nbsp;is a non-negative integer, then&nbsp;<code>abs(x) = x</code>.</li></ul>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,-3,2,3,-4]
<strong>Output:</strong> 5
<strong>Explanation:</strong> The subarray [2,3] has absolute sum = abs(2+3) = abs(5) = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,-5,1,-4,3,-2]
<strong>Output:</strong> 8
<strong>Explanation:</strong> The subarray [-5,1,-4] has absolute sum = abs(-5+1-4) = abs(-8) = 8.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>-10<sup>4</sup>&nbsp;&lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<p>ans = max{abs(prefix_sum[i] &#8211; max(prefix_sum[0:i])), abs(prefix_sum &#8211; min(prefix_sum[0:i])}</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 maxAbsoluteSum(vector&lt;int&gt;&amp; nums) {
    int lo = 0;
    int hi = 0;
    int s = 0;
    int ans = 0;
    for (int x : nums) {
      s += x;
      ans = max({ans, abs(s - lo), abs(s - hi)});
      hi = max(hi, s);
      lo = min(lo, s);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/">花花酱 LeetCode 1749. Maximum Absolute Sum of Any Subarray</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/algorithms/array/leetcode-1749-maximum-absolute-sum-of-any-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones</title>
		<link>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/</link>
					<comments>https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 27 Dec 2020 07:56:26 +0000</pubDate>
				<category><![CDATA[Sliding Window]]></category>
		<category><![CDATA[consecutive]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[sliding window]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7853</guid>

					<description><![CDATA[<p>You are given an integer array,&#160;nums, and an integer&#160;k.&#160;nums&#160;comprises of only&#160;0&#8216;s and&#160;1&#8216;s. In one move, you can choose two&#160;adjacent&#160;indices and swap their values. Return&#160;the&#160;minimum&#160;number of&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/">花花酱 LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones</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>You are given an integer array,&nbsp;<code>nums</code>, and an integer&nbsp;<code>k</code>.&nbsp;<code>nums</code>&nbsp;comprises of only&nbsp;<code>0</code>&#8216;s and&nbsp;<code>1</code>&#8216;s. In one move, you can choose two&nbsp;<strong>adjacent</strong>&nbsp;indices and swap their values.</p>



<p>Return&nbsp;<em>the&nbsp;<strong>minimum</strong>&nbsp;number of moves required so that&nbsp;</em><code>nums</code><em>&nbsp;has&nbsp;</em><code>k</code><em>&nbsp;<strong>consecutive</strong>&nbsp;</em><code>1</code><em>&#8216;s</em>.</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,1,0,1], k = 2
<strong>Output:</strong> 1
<strong>Explanation:</strong> In 1 move, nums could be [1,0,0,0,1,1] and have 2 consecutive 1's.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,0,0,0,0,0,1,1], k = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong> In 5 moves, the leftmost 1 can be shifted right until nums = [0,0,0,0,0,1,1,1].
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,0,1], k = 2
<strong>Output:</strong> 0
<strong>Explanation:</strong> nums already has 2 consecutive 1's.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>nums[i]</code>&nbsp;is&nbsp;<code>0</code>&nbsp;or&nbsp;<code>1</code>.</li><li><code>1 &lt;= k &lt;= sum(nums)</code></li></ul>



<h2><strong>Solution: Prefix Sum + Sliding Window</strong></h2>



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



<p>We only care positions of 1s, we can move one element from position x to y (assuming x + 1 ~ y are all zeros) in y &#8211; x steps. e.g. [0 0 1 0 0 0 1] =&gt; [0 0 0 0 0 1 1], move first 1 at position 2 to position 5, cost is 5 &#8211; 2 = 3.</p>



<p>Given a size k window of indices of ones, the optimal solution it to use the median number as center. We can compute the cost to form consecutive numbers:</p>



<p>e.g. [1 4 7 9 10] =&gt; [5 6 7 8 9] cost = (5 &#8211; 1) + (6 &#8211; 4) + (9 &#8211; 8) + (10 &#8211; 9) = 8</p>



<p>However, naive solution takes O(n*k) =&gt; TLE.</p>



<p>We can use prefix sum to compute the cost of a window in O(1) to reduce time complexity to O(n)</p>



<p>First, in order to use sliding window, we change the target of every number in the window to the median number.<br>e.g. [1 4 7 9 10] =&gt; [7 7 7 7 7] cost = (7 &#8211; 1) + (7 &#8211; 4) + (7 &#8211; 7) + (9 &#8211; 7) + (10 &#8211; 7) = (9 + 10) &#8211; (1 + 4) = right &#8211; left. <br>[5 6 7 8 9] =&gt; [7 7 7 7 7] takes extra 2 + 1 + 1 + 2 = 6 steps =  (k / 2) * ((k + 1) / 2), these extra steps should be deducted from the final answer. </p>



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

<pre class="crayon-plain-tag">class Solution {
public:
  int minMoves(vector&lt;int&gt;&amp; nums, int k) {
    vector&lt;long&gt; s(1);
    for (int i = 0; i &lt; nums.size(); ++i)
      if (nums[i])
        s.push_back(s.back() + i);
    const int n = s.size();
    long ans = 1e10;
    const int m1 = k / 2, m2 = (k + 1) / 2;
    for (int i = 0; i + k &lt; n; ++i) {
      const long right = s[i + k] - s[i + m1];
      const long left = s[i + m2] - s[i];
      ans = min(ans, right - left);
    }
    return ans - m1 * m2;
  }
};</pre>

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

<pre class="crayon-plain-tag">class Solution:
  def minMoves(self, nums: List[int], k: int) -&gt; int:
    ans = 1e10
    s = [0]    
    for i, v in enumerate(nums):
      if v: s.append(s[-1] + i)
    n = len(s)
    m1 = k // 2
    m2 = (k + 1) // 2
    for i in range(n - k):
      right = s[i + k] - s[i + m1]
      left = s[i + m2] - s[i]
      ans = min(ans, right - left)
    return ans - m1 * m2</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/sliding-window/leetcode-1703-minimum-adjacent-swaps-for-k-consecutive-ones/">花花酱 LeetCode 1703. Minimum Adjacent Swaps for K Consecutive Ones</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-1703-minimum-adjacent-swaps-for-k-consecutive-ones/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</title>
		<link>https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/</link>
					<comments>https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 13 Dec 2020 00:48:31 +0000</pubDate>
				<category><![CDATA[Math]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[O(n)]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7790</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;sorted in&#160;non-decreasing&#160;order. Build and return&#160;an integer array&#160;result&#160;with the same length as&#160;nums&#160;such that&#160;result[i]&#160;is equal to the&#160;summation of absolute differences&#160;between&#160;nums[i]&#160;and all the&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/">花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</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>You are given an integer array&nbsp;<code>nums</code>&nbsp;sorted in&nbsp;<strong>non-decreasing</strong>&nbsp;order.</p>



<p>Build and return&nbsp;<em>an integer array&nbsp;</em><code>result</code><em>&nbsp;with the same length as&nbsp;</em><code>nums</code><em>&nbsp;such that&nbsp;</em><code>result[i]</code><em>&nbsp;is equal to the&nbsp;<strong>summation of absolute differences</strong>&nbsp;between&nbsp;</em><code>nums[i]</code><em>&nbsp;and all the other elements in the array.</em></p>



<p>In other words,&nbsp;<code>result[i]</code>&nbsp;is equal to&nbsp;<code>sum(|nums[i]-nums[j]|)</code>&nbsp;where&nbsp;<code>0 &lt;= j &lt; nums.length</code>&nbsp;and&nbsp;<code>j != i</code>&nbsp;(<strong>0-indexed</strong>).</p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,3,5]
<strong>Output:</strong> [4,3,5]
<strong>Explanation:</strong> Assuming the arrays are 0-indexed, then
result[0] = |2-2| + |2-3| + |2-5| = 0 + 1 + 3 = 4,
result[1] = |3-2| + |3-3| + |3-5| = 1 + 0 + 2 = 3,
result[2] = |5-2| + |5-3| + |5-5| = 3 + 2 + 0 = 5.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,4,6,8,10]
<strong>Output:</strong> [24,15,13,15,21]
</pre>



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



<ul><li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= nums[i + 1] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<p>Let s[i] denote sum(num[i] &#8211; num[j]) 0 &lt;= j &lt;= i<br>s[i] = s[i &#8211; 1] + (num[i] &#8211; num[i &#8211; 1]) * i<br>Let l[i] denote sum(nums[j] &#8211; nums[i]) i &lt;= j &lt; n<br>l[i] = l[i + 1] + (nums[i + 1] &#8211; num[i]) * (n &#8211; i &#8211; 1)<br>ans[i] = s[i] + l[i]</p>



<p>e.g. 1, 3, 7, 9<br>s[0] = 0<br>s[1] = 0 + (3 &#8211; 1) * 1 = 2<br>s[2] = 2 + (7 &#8211; 3) * 2 = 10<br>s[3] = 10 + (9 &#8211; 7) * 3 = 16<br>l[3] = 0<br>l[2] = 0 + (9 &#8211; 7) * 1 = 2<br>l[1] = 2 + (7 &#8211; 3) * 2 = 10<br>l[0] = 10 + (3 &#8211; 1) *  3 = 16</p>



<p>ans = [16, 12, 12, 16]</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:
  vector&lt;int&gt; getSumAbsoluteDifferences(vector&lt;int&gt;&amp; nums) {
    const int n = nums.size();
    vector&lt;int&gt; ans(n);    
    for (int i = 1, sum = 0; i &lt; n; ++i)
      ans[i] += (sum += (nums[i] - nums[i - 1]) * i);
    for (int i = n - 2, sum = 0; i &gt;= 0; --i)
      ans[i] += (sum += (nums[i + 1] - nums[i]) * (n - i - 1));
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/">花花酱 LeetCode 1685. Sum of Absolute Differences in a Sorted Array</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/math/leetcode-1685-sum-of-absolute-differences-in-a-sorted-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1664. Ways to Make a Fair Array</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1664-ways-to-make-a-fair-array/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1664-ways-to-make-a-fair-array/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 22 Nov 2020 22:47:12 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[prefix sum]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=7702</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums. You can choose&#160;exactly one&#160;index (0-indexed) and remove the element. Notice that the index of the elements may change after&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1664-ways-to-make-a-fair-array/">花花酱 LeetCode 1664. Ways to Make a Fair Array</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>You are given an integer array&nbsp;<code>nums</code>. You can choose&nbsp;<strong>exactly one</strong>&nbsp;index (<strong>0-indexed</strong>) and remove the element. Notice that the index of the elements may change after the removal.</p>



<p>For example, if&nbsp;<code>nums = [6,1,7,4,1]</code>:</p>



<ul><li>Choosing to remove index&nbsp;<code>1</code>&nbsp;results in&nbsp;<code>nums = [6,7,4,1]</code>.</li><li>Choosing to remove index&nbsp;<code>2</code>&nbsp;results in&nbsp;<code>nums = [6,1,4,1]</code>.</li><li>Choosing to remove index&nbsp;<code>4</code>&nbsp;results in&nbsp;<code>nums = [6,1,7,4]</code>.</li></ul>



<p>An array is&nbsp;<strong>fair</strong>&nbsp;if the sum of the odd-indexed values equals the sum of the even-indexed values.</p>



<p>Return the&nbsp;<em><strong>number</strong>&nbsp;of indices that you could choose such that after the removal,&nbsp;</em><code>nums</code><em>is&nbsp;<strong>fair</strong>.</em></p>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [2,1,6,4]
<strong>Output:</strong> 1
<strong>Explanation:</strong>
Remove index 0: [1,6,4] -&gt; Even sum: 1 + 4 = 5. Odd sum: 6. Not fair.
Remove index 1: [2,6,4] -&gt; Even sum: 2 + 4 = 6. Odd sum: 6. Fair.
Remove index 2: [2,1,4] -&gt; Even sum: 2 + 4 = 6. Odd sum: 1. Not fair.
Remove index 3: [2,1,6] -&gt; Even sum: 2 + 6 = 8. Odd sum: 1. Not fair.
There is 1 index that you can remove to make nums fair.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,1,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong>&nbsp;You can remove any index and the remaining array is fair.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> 0
<strong>Explanation:</strong>&nbsp;You cannot make a fair array after removing any index.
</pre>



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



<ul><li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li><li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li></ul>



<h2><strong>Solution: Prefix Sum</strong></h2>



<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 waysToMakeFair(vector&lt;int&gt;&amp; nums) {
    int n = nums.size();
    vector&lt;int&gt; odds(n + 1);
    vector&lt;int&gt; evens(n + 1);
    for (int i = 0; i &lt; n; ++i) {      
      odds[i + 1] = odds[i] + (i % 2 == 1) * nums[i];
      evens[i + 1] = evens[i] + (i % 2 == 0) * nums[i];      
    }
    int ans = 0;
    for (int i = 0; i &lt; n; ++i) {
      const int odd = odds[i] + (evens[n] - evens[i + 1]);
      const int even = evens[i] + (odds[n] - odds[i + 1]);
      ans += odd == even;
    }
    return ans;
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1664-ways-to-make-a-fair-array/">花花酱 LeetCode 1664. Ways to Make a Fair Array</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/algorithms/array/leetcode-1664-ways-to-make-a-fair-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
