<?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>range query Archives - Huahua&#039;s Tech Road</title>
	<atom:link href="https://zxi.mytechroad.com/blog/tag/range-query/feed/" rel="self" type="application/rss+xml" />
	<link>https://zxi.mytechroad.com/blog/tag/range-query/</link>
	<description></description>
	<lastBuildDate>Mon, 12 Sep 2022 05:17:21 +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>range query Archives - Huahua&#039;s Tech Road</title>
	<link>https://zxi.mytechroad.com/blog/tag/range-query/</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>花花酱 LeetCode 2407. Longest Increasing Subsequence II</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2407-longest-increasing-subsequence-ii/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2407-longest-increasing-subsequence-ii/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Mon, 12 Sep 2022 05:16:09 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[range query]]></category>
		<category><![CDATA[segment tree]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=9817</guid>

					<description><![CDATA[<p>You are given an integer array&#160;nums&#160;and an integer&#160;k. Find the longest subsequence of&#160;nums&#160;that meets the following requirements: The subsequence is&#160;strictly increasing&#160;and The difference between adjacent&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2407-longest-increasing-subsequence-ii/">花花酱 LeetCode 2407. Longest Increasing Subsequence II</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;and an integer&nbsp;<code>k</code>.</p>



<p>Find the longest subsequence of&nbsp;<code>nums</code>&nbsp;that meets the following requirements:</p>



<ul><li>The subsequence is&nbsp;<strong>strictly increasing</strong>&nbsp;and</li><li>The difference between adjacent elements in the subsequence is&nbsp;<strong>at most</strong>&nbsp;<code>k</code>.</li></ul>



<p>Return<em>&nbsp;the length of the&nbsp;<strong>longest</strong>&nbsp;<strong>subsequence</strong>&nbsp;that meets the requirements.</em></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,2,1,4,3,4,5,8,15], k = 3
<strong>Output:</strong> 5
<strong>Explanation:</strong>
The longest subsequence that meets the requirements is [1,3,4,5,8].
The subsequence has a length of 5, so we return 5.
Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [7,4,5,1,8,12,4,7], k = 5
<strong>Output:</strong> 4
<strong>Explanation:</strong>
The longest subsequence that meets the requirements is [4,5,8,12].
The subsequence has a length of 4, so we return 4.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [1,5], k = 1
<strong>Output:</strong> 1
<strong>Explanation:</strong>
The longest subsequence that meets the requirements is [1].
The subsequence has a length of 1, so we return 1.
</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], k &lt;= 10<sup>5</sup></code></li></ul>



<h2><strong>Solution: DP + Segment Tree | Max range query</strong></h2>



<p>Let dp[i] := length of LIS end with number i.<br>dp[i] = 1 + max(dp[i-k:i])</p>



<p>Naive dp takes O(n*k) time which will cause TLE.</p>



<p>We can use segment tree to speed up the max range query to log(m), where m is the max value of the array.</p>



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



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

<pre class="crayon-plain-tag">// Author: Huahua
class Solution {
public:
  int lengthOfLIS(vector&lt;int&gt;&amp; nums, int k) {
    const int n = *max_element(begin(nums), end(nums));
    vector&lt;int&gt; dp(2 * (n + 1));
    auto query = [&amp;](int l, int r) -&gt; int {
      int ans = 0;
      for (l += n, r += n; l &lt; r; l &gt;&gt;= 1, r &gt;&gt;= 1) {
        if (l &amp; 1) ans = max(ans, dp[l++]);      
        if (r &amp; 1) ans = max(ans, dp[--r]);
      }
      return ans;
    };
    auto update = [&amp;](int i, int val) -&gt; void {
      dp[i += n] = val;
      while (i &gt; 1) {
        i &gt;&gt;= 1;
        dp[i] = max(dp[i * 2], dp[i * 2 + 1]);
      }
    };        
    int ans = 0;
    for (int x : nums) {
      int cur = 1 + query(max(1, x - k), x);
      update(x, cur);
      ans = max(ans, cur);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-2407-longest-increasing-subsequence-ii/">花花酱 LeetCode 2407. Longest Increasing Subsequence II</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-2407-longest-increasing-subsequence-ii/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[<p>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;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/">花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2><strong><a href="http://2106. Maximum Fruits Harvested After at Most K Steps">Problem</a></strong></h2>



<p></p>



<h2><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="crayon-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><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="crayon-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>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-2106-maximum-fruits-harvested-after-at-most-k-steps/">花花酱 LeetCode 2106. Maximum Fruits Harvested After at Most K Steps</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-2106-maximum-fruits-harvested-after-at-most-k-steps/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 2055. Plates Between Candles</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2055-plates-between-candles/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2055-plates-between-candles/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Thu, 04 Nov 2021 02:21:13 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[range query]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8657</guid>

					<description><![CDATA[<p>There is a long table with a line of plates and candles arranged on top of it. You are given a&#160;0-indexed&#160;string&#160;s&#160;consisting of characters&#160;'*'&#160;and&#160;'&#124;'&#160;only, where a&#160;'*'&#160;represents&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2055-plates-between-candles/">花花酱 LeetCode 2055. Plates Between Candles</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>There is a long table with a line of plates and candles arranged on top of it. You are given a&nbsp;<strong>0-indexed</strong>&nbsp;string&nbsp;<code>s</code>&nbsp;consisting of characters&nbsp;<code>'*'</code>&nbsp;and&nbsp;<code>'|'</code>&nbsp;only, where a&nbsp;<code>'*'</code>&nbsp;represents a&nbsp;<strong>plate</strong>&nbsp;and a&nbsp;<code>'|'</code>&nbsp;represents a&nbsp;<strong>candle</strong>.</p>



<p>You are also given a&nbsp;<strong>0-indexed</strong>&nbsp;2D integer array&nbsp;<code>queries</code>&nbsp;where&nbsp;<code>queries[i] = [left<sub>i</sub>, right<sub>i</sub>]</code>&nbsp;denotes the&nbsp;<strong>substring</strong>&nbsp;<code>s[left<sub>i</sub>...right<sub>i</sub>]</code>&nbsp;(<strong>inclusive</strong>). For each query, you need to find the&nbsp;<strong>number</strong>&nbsp;of plates&nbsp;<strong>between candles</strong>&nbsp;that are&nbsp;<strong>in the substring</strong>. A plate is considered&nbsp;<strong>between candles</strong>&nbsp;if there is at least one candle to its left&nbsp;<strong>and</strong>&nbsp;at least one candle to its right&nbsp;<strong>in the substring</strong>.</p>



<ul><li>For example,&nbsp;<code>s = "||**||**|*"</code>, and a query&nbsp;<code>[3, 8]</code>&nbsp;denotes the substring&nbsp;<code>"*||<strong><u>**</u></strong>|"</code>. The number of plates between candles in this substring is&nbsp;<code>2</code>, as each of the two plates has at least one candle&nbsp;<strong>in the substring</strong>&nbsp;to its left&nbsp;<strong>and</strong>&nbsp;right.</li></ul>



<p>Return&nbsp;<em>an integer array</em>&nbsp;<code>answer</code>&nbsp;<em>where</em>&nbsp;<code>answer[i]</code>&nbsp;<em>is the answer to the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>query</em>.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/04/ex-1.png" alt="ex-1"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "**|**|***|", queries = [[2,5],[5,9]]
<strong>Output:</strong> [2,3]
<strong>Explanation:</strong>
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
</pre>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2021/10/04/ex-2.png" alt="ex-2"/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> s = "***|**|*****|**||**|*", queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
<strong>Output:</strong> [9,0,0,0,0]
<strong>Explanation:</strong>
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.
</pre>



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



<ul><li><code>3 &lt;= s.length &lt;= 10<sup>5</sup></code></li><li><code>s</code>&nbsp;consists of&nbsp;<code>'*'</code>&nbsp;and&nbsp;<code>'|'</code>&nbsp;characters.</li><li><code>1 &lt;= queries.length &lt;= 10<sup>5</sup></code></li><li><code>queries[i].length == 2</code></li><li><code>0 &lt;= left<sub>i</sub>&nbsp;&lt;= right<sub>i</sub>&nbsp;&lt; s.length</code></li></ul>



<h2><strong>Solution: Binary Search</strong></h2>



<p>Store the indices of all candles into an array idx.</p>



<p>For each query q: <br>1. Find the left most candle whose index is greater or equal to left as l.<br>2. Find the left most candle whose index is greater than right, choose the previous candle as r.</p>



<p>[idx[l], idx[r]] is the range that are elements between two candles , there are (idx[r] &#8211; idx[l] + 1) elements in total and there are (r &#8211; l + 1) candles in the range. So the number of plates is (idx[r] &#8211; idx[l] + 1) &#8211;  (r &#8211; l + 1) or (idx[r] &#8211; idx[l]) &#8211; (r &#8211; l)</p>



<p>Time complexity: O(qlogn)<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; platesBetweenCandles(string s, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {
    vector&lt;int&gt; idx;
    for (size_t i = 0; i &lt; s.size(); ++i)
      if (s[i] == '|') idx.push_back(i);
    vector&lt;int&gt; ans;
    for (const auto&amp; q : queries) {
      const int l = lower_bound(begin(idx), end(idx), q[0]) - begin(idx);
      const int r = upper_bound(begin(idx), end(idx), q[1]) - begin(idx) - 1;      
      ans.push_back(l &gt;= r ? 0 : (idx[r] - idx[l]) - (r - l));
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-2055-plates-between-candles/">花花酱 LeetCode 2055. Plates Between Candles</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/binary-search/leetcode-2055-plates-between-candles/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1906. Minimum Absolute Difference Queries</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1906-minimum-absolute-difference-queries/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1906-minimum-absolute-difference-queries/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 15 Aug 2021 23:26:14 +0000</pubDate>
				<category><![CDATA[Binary Search]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[range query]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=8590</guid>

					<description><![CDATA[<p>The&#160;minimum absolute difference&#160;of an array&#160;a&#160;is defined as the&#160;minimum value&#160;of&#160;&#124;a[i] - a[j]&#124;, where&#160;0 &#60;= i &#60; j &#60; a.length&#160;and&#160;a[i] != a[j]. If all elements of&#160;a&#160;are the&#160;same,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1906-minimum-absolute-difference-queries/">花花酱 LeetCode 1906. Minimum Absolute Difference Queries</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>The&nbsp;<strong>minimum absolute difference</strong>&nbsp;of an array&nbsp;<code>a</code>&nbsp;is defined as the&nbsp;<strong>minimum value</strong>&nbsp;of&nbsp;<code>|a[i] - a[j]|</code>, where&nbsp;<code>0 &lt;= i &lt; j &lt; a.length</code>&nbsp;and&nbsp;<code>a[i] != a[j]</code>. If all elements of&nbsp;<code>a</code>&nbsp;are the&nbsp;<strong>same</strong>, the minimum absolute difference is&nbsp;<code>-1</code>.</p>



<ul><li>For example, the minimum absolute difference of the array&nbsp;<code>[5,<u>2</u>,<u>3</u>,7,2]</code>&nbsp;is&nbsp;<code>|2 - 3| = 1</code>. Note that it is not&nbsp;<code>0</code>&nbsp;because&nbsp;<code>a[i]</code>&nbsp;and&nbsp;<code>a[j]</code>&nbsp;must be different.</li></ul>



<p>You are given an integer array&nbsp;<code>nums</code>&nbsp;and the array&nbsp;<code>queries</code>&nbsp;where&nbsp;<code>queries[i] = [l<sub>i</sub>, r<sub>i</sub>]</code>. For each query&nbsp;<code>i</code>, compute the&nbsp;<strong>minimum absolute difference</strong>&nbsp;of the&nbsp;<strong>subarray</strong>&nbsp;<code>nums[l<sub>i</sub>...r<sub>i</sub>]</code>&nbsp;containing the elements of&nbsp;<code>nums</code>&nbsp;between the&nbsp;<strong>0-based</strong>&nbsp;indices&nbsp;<code>l<sub>i</sub></code>&nbsp;and&nbsp;<code>r<sub>i</sub></code>&nbsp;(<strong>inclusive</strong>).</p>



<p>Return&nbsp;<em>an&nbsp;<strong>array</strong>&nbsp;</em><code>ans</code>&nbsp;<em>where</em>&nbsp;<code>ans[i]</code>&nbsp;<em>is the answer to the</em>&nbsp;<code>i<sup>th</sup></code>&nbsp;<em>query</em>.</p>



<p>A&nbsp;<strong>subarray</strong>&nbsp;is a contiguous sequence of elements in an array.</p>



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



<ul><li><code>x</code>&nbsp;if&nbsp;<code>x &gt;= 0</code>.</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> nums = [1,3,4,8], queries = [[0,1],[1,2],[2,3],[0,3]]
<strong>Output:</strong> [2,1,4,1]
<strong>Explanation:</strong> The queries are processed as follows:
- queries[0] = [0,1]: The subarray is [1,3] and the minimum absolute difference is |1-3| = 2.
- queries[1] = [1,2]: The subarray is [3,4] and the minimum absolute difference is |3-4| = 1.
- queries[2] = [2,3]: The subarray is [4,8] and the minimum absolute difference is |4-8| = 4.
- queries[3] = [0,3]: The subarray is [1,3,4,8] and the minimum absolute difference is |3-4| = 1.
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> nums = [4,5,2,2,7,10], queries = [[2,3],[0,2],[0,5],[3,5]]
<strong>Output:</strong> [-1,1,1,3]
<strong>Explanation: </strong>The queries are processed as follows:
- queries[0] = [2,3]: The subarray is [2,2] and the minimum absolute difference is -1 because all the
  elements are the same.
- queries[1] = [0,2]: The subarray is [4,5,2] and the minimum absolute difference is |4-5| = 1.
- queries[2] = [0,5]: The subarray is [4,5,2,2,7,10] and the minimum absolute difference is |4-5| = 1.
- queries[3] = [3,5]: The subarray is [2,7,10] and the minimum absolute difference is |7-10| = 3.
</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;= 100</code></li><li><code>1 &lt;= queries.length &lt;= 2&nbsp;* 10<sup>4</sup></code></li><li><code>0 &lt;= l<sub>i</sub>&nbsp;&lt; r<sub>i</sub>&nbsp;&lt; nums.length</code></li></ul>



<h2><strong>Solution: Binary Search</strong></h2>



<p>Since the value range of num is quiet small [1~100], we can store the indices for each value. <br>[2, 1, 2, 2, 3] =&gt; {1: [1], 2: [0, 2, 3]: 3: [4]}.</p>



<p>For each query, we try all possible value b. Check whether b is the query range using binary search, we also keep tracking the previous available value a, ans will be min{b &#8211; a}.</p>



<p>Time complexity: O(n + q * 100 * log(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; minDifference(vector&lt;int&gt;&amp; nums, vector&lt;vector&lt;int&gt;&gt;&amp; queries) {    
    constexpr int kMax = 100;
    const int n = nums.size();
    vector&lt;vector&lt;int&gt;&gt; idx(kMax + 1);
    for (int i = 0; i &lt; n; ++i)
      idx[nums[i]].push_back(i);
    vector&lt;int&gt; ans;
    for (const auto&amp; q: queries) {      
      int diff = INT_MAX;
      for (int a = 0, b = 1; b &lt;= kMax; ++b) {
        auto it = lower_bound(begin(idx[b]), end(idx[b]), q[0]);
        if (it == end(idx[b]) || *it &gt; q[1]) continue;
        if (a) diff = min(diff, b - a);
        a = b;
      }
      ans.push_back(diff == INT_MAX ? -1 : diff);
    }
    return ans;
  }
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-1906-minimum-absolute-difference-queries/">花花酱 LeetCode 1906. Minimum Absolute Difference Queries</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/binary-search/leetcode-1906-minimum-absolute-difference-queries/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Wed, 18 Dec 2019 04:12:31 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[binary search]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[matrix]]></category>
		<category><![CDATA[medium]]></category>
		<category><![CDATA[range query]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5970</guid>

					<description><![CDATA[<p>Given a&#160;m x n&#160;matrix&#160;mat&#160;and an integer&#160;threshold. Return the maximum side-length of a square with a sum less than or equal to&#160;threshold&#160;or return&#160;0&#160;if there is no&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/">花花酱 LeetCode 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold</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;<code>m x n</code>&nbsp;matrix&nbsp;<code>mat</code>&nbsp;and an integer&nbsp;<code>threshold</code>. Return the maximum side-length of a square with a sum less than or equal to&nbsp;<code>threshold</code>&nbsp;or return&nbsp;<strong>0</strong>&nbsp;if there is no such square.</p>



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



<figure class="wp-block-image"><img src="https://assets.leetcode.com/uploads/2019/12/05/e1.png" alt=""/></figure>



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> The maximum side length of square with sum less than 4 is 2 as shown.
</pre>



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



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



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6
<strong>Output:</strong> 3
</pre>



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



<pre class="wp-block-preformatted;crayon:false"><strong>Input:</strong> mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184
<strong>Output:</strong> 2
</pre>



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



<ul><li><code>1 &lt;= m, n &lt;= 300</code></li><li><code>m == mat.length</code></li><li><code>n == mat[i].length</code></li><li><code>0 &lt;= mat[i][j] &lt;= 10000</code></li><li><code>0 &lt;= threshold&nbsp;&lt;= 10^5</code></li></ul>



<h2><strong>Solution: DP + Brute Force</strong></h2>



<p>Precompute the sums of sub-matrixes whose left-top corner is at (0,0).</p>



<p>Try all possible left-top corner and sizes.</p>



<p>Time complexity: O(m*n*min(m,n))<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, 148 ms
class Solution {
public:
  int maxSideLength(vector&lt;vector&lt;int&gt;&gt;&amp; mat, int threshold) {
    const int m = mat.size();
    const int n = mat[0].size();
    
    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n + 1));
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x)
        dp[y][x] = dp[y][x - 1] + dp[y - 1][x]  - dp[y - 1][x - 1] + mat[y - 1][x - 1];
    
    auto rangeSum = [&amp;](int x1, int y1, int x2, int y2) {
      return dp[y2][x2] - dp[y2][x1 - 1] - dp[y1 - 1][x2] + dp[y1 - 1][x1 - 1];
    };
    
    int ans = 0;
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x)
        for (int k = 0; y + k &lt;= m &amp;&amp; x + k &lt;= n; ++k) {
          if (rangeSum(x, y, x + k, y + k) &gt; threshold) break;
          ans = max(ans, k + 1);
        }
    return ans;  
  }
};</pre>
</div></div>



<h2><strong>Solution 2: Binary Search</strong></h2>



<p>Search for the smallest size k that is greater than the threshold, ans = k &#8211; 1.</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 116 ms
class Solution {
public:
  int maxSideLength(vector&lt;vector&lt;int&gt;&gt;&amp; mat, int threshold) {
    const int m = mat.size();
    const int n = mat[0].size();
    
    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n + 1));
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x)
        dp[y][x] = dp[y][x - 1] + dp[y - 1][x]  - dp[y - 1][x - 1] + mat[y - 1][x - 1];
    
    auto rangeSum = [&amp;](int x1, int y1, int x2, int y2) {
      return dp[y2][x2] - dp[y2][x1 - 1] - dp[y1 - 1][x2] + dp[y1 - 1][x1 - 1];
    };
    
    int ans = 0;
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x) {
        int l = 0;
        int r = min(m - y, n - x) + 1;
        while (l &lt; r) {
          int m = l + (r - l) / 2;
          // Find smllest l that &gt; threshold, ans = (l + 1) - 1
          if (rangeSum(x, y, x + m, y + m) &gt; threshold)
            r = m;
          else
            l = m + 1;
        }
        ans = max(ans, (l + 1) - 1);
      }
    return ans;  
  }
};</pre>
</div></div>



<h2><strong>Solution 3: Bounded Search</strong></h2>



<p>Time complexity: O(m*n + min(m,n))</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 148 ms
class Solution {
public:
  int maxSideLength(vector&lt;vector&lt;int&gt;&gt;&amp; mat, int threshold) {
    const int m = mat.size();
    const int n = mat[0].size();
    
    vector&lt;vector&lt;int&gt;&gt; dp(m + 1, vector&lt;int&gt;(n + 1));
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x)
        dp[y][x] = dp[y][x - 1] + dp[y - 1][x]  - dp[y - 1][x - 1] + mat[y - 1][x - 1];
    
    auto rangeSum = [&amp;](int x1, int y1, int x2, int y2) {
      return dp[y2][x2] - dp[y2][x1 - 1] - dp[y1 - 1][x2] + dp[y1 - 1][x1 - 1];
    };
    
    int ans = 0;
    for (int y = 1; y &lt;= m; ++y)
      for (int x = 1; x &lt;= n; ++x)
        for (int k = ans; y + k &lt;= m &amp;&amp; x + k &lt;= n; ++k) {
          if (rangeSum(x, y, x + k, y + k) &gt; threshold) break;
          ans = max(ans, k + 1);
        }
    return ans;  
  }
};</pre>
</div></div>



<p></p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/">花花酱 LeetCode 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold</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-1292-maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 1157. Online Majority Element In Subarray</title>
		<link>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1157-online-majority-element-in-subarray/</link>
					<comments>https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1157-online-majority-element-in-subarray/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Sun, 11 Aug 2019 04:41:08 +0000</pubDate>
				<category><![CDATA[Array]]></category>
		<category><![CDATA[hard]]></category>
		<category><![CDATA[range query]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=5410</guid>

					<description><![CDATA[<p>Implementing the class&#160;MajorityChecker, which has the following API: MajorityChecker(int[] arr)&#160;constructs an instance of MajorityChecker with the given array&#160;arr; int query(int left, int right, int threshold)&#160;has&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1157-online-majority-element-in-subarray/">花花酱 LeetCode 1157. Online Majority Element In 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>Implementing the class&nbsp;<code>MajorityChecker</code>, which has the following API:</p>



<ul><li><code>MajorityChecker(int[] arr)</code>&nbsp;constructs an instance of MajorityChecker with the given array&nbsp;<code>arr</code>;</li><li><code>int query(int left, int right, int threshold)</code>&nbsp;has arguments&nbsp;such that:<ul><li><code>0 &lt;= left&nbsp;&lt;= right&nbsp;&lt; arr.length</code>&nbsp;representing a subarray of&nbsp;<code>arr</code>;</li><li><code>2 * threshold &gt; right - left + 1</code>, ie. the threshold is always a strict majority of the length of&nbsp;the subarray</li></ul></li></ul>



<p>Each&nbsp;<code>query(...)</code>&nbsp;returns the element in&nbsp;<code>arr[left], arr[left+1], ..., arr[right]</code>that occurs at least&nbsp;<code>threshold</code>&nbsp;times, or&nbsp;<code>-1</code>&nbsp;if no such element exists.</p>



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



<pre class="wp-block-preformatted;crayon:false">MajorityChecker majorityChecker = new MajorityChecker([1,1,2,2,1,1]);
majorityChecker.query(0,5,4); // returns 1
majorityChecker.query(0,3,3); // returns -1
majorityChecker.query(2,3,2); // returns 2
</pre>



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



<ul><li><code>1 &lt;= arr.length &lt;=&nbsp;20000</code></li><li><code>1 &lt;= arr[i]&nbsp;&lt;=&nbsp;20000</code></li><li>For each query,&nbsp;<code>0 &lt;= left &lt;= right &lt; len(arr)</code></li><li>For each query,&nbsp;<code>2 * threshold &gt; right - left + 1</code></li><li>The number of queries is at most&nbsp;<code>10000</code></li></ul>



<h2><strong>Solution 0: Brute Force TLE</strong></h2>



<p>For each range, find the majority element in O(n) time / O(n) or O(1) space.</p>



<h2><strong>Solution 1: Cache the range result</strong></h2>



<p>Cache the result for each range: mode and frequency</p>



<p>Time complexity: <br>init: O(1)<br>query: O(|right &#8211; left|)<br>total queries: O(sum(right_i &#8211; left_i)), right_i, left_i are bounds of unique ranges.<br>Space complexity: <br>init: O(1)<br>query: O(20000)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 568ms, 39.6 MB
class MajorityChecker {
public:
  MajorityChecker(vector&lt;int&gt;&amp; arr):nums(arr) {}

  int query(int left, int right, int threshold) {        
    int key = left * 20000 + right;
    if (!seen.count(key)) {
      int c[20001] = {0};
      int best = (right - left) / 2;
      int best_num = -1;
      for (int i = left; i &lt;= right; ++i) {
        if (++c[nums[i]] &gt; best) {
          best = c[nums[i]];
          best_num = nums[i];
        }
      }
      seen[key] = {best_num, best};
    }
    return seen[key].second &gt;= threshold ? seen[key].first : -1;
  }
private:
  unordered_map&lt;int, pair&lt;int, int&gt;&gt; seen;
  const vector&lt;int&gt;&amp; nums;
};</pre>
</div></div>



<h2><strong>Solution 2: HashTable + binary search</strong></h2>



<p>Preprocessing: use a hashtable to store the indices of each element. And sort by frequency of the element in descending order.<br>Query: iterator over (total_freq, num) pair, if freq &gt;= threshold do a binary search to find the frequency of the given range for num in O(logn).</p>



<p>Time complexity: <br>Init: O(nlogn)<br>Query: worst case: O(nlogn), best case: O(logn)</p>



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

<pre class="crayon-plain-tag">// Author: Huahua, 156 ms, 44.7MB
class MajorityChecker {
public:
  MajorityChecker(vector&lt;int&gt;&amp; arr):nums(arr) {
    const int max_n = *max_element(begin(nums), end(nums));
    m = vector&lt;vector&lt;int&gt;&gt;(max_n + 1);
    for (int i = 0; i &lt; nums.size(); ++i) m[nums[i]].push_back(i);    
    for (int n = 1; n &lt;= max_n; ++n) {
      if (m[n].size()) f.emplace_back(m[n].size(), n);
    }
    sort(rbegin(f), rend(f));    
  }

  int query(int left, int right, int threshold) {
    for (const auto&amp; p : f) {
      if (p.first &lt; threshold) return -1;
      int n = p.second;
      const auto&amp; idx = m[n];
      int count = upper_bound(begin(idx), end(idx), right) - lower_bound(begin(idx), end(idx), left);
      if (count &gt;= threshold) return n;
    }
    return -1;
  }
private:
  const vector&lt;int&gt;&amp; nums;
  vector&lt;vector&lt;int&gt;&gt; m; // num -&gt; {indices}
  vector&lt;pair&lt;int, int&gt;&gt; f; // {freq, num}
};</pre>
</div></div>



<h2><strong>Solution 2+: Randomization</strong></h2>



<p>Randomly pick a num in range [left, right] and check its freq, try k (e.g. 30) times. If a majority element exists, you should find it with error rate 1/2^k.</p>



<p>Time complexity:<br>Init: O(n)<br>Query: O(30 * logn)<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, 240ms, 45.6MB
class MajorityChecker {
public:
  MajorityChecker(vector&lt;int&gt;&amp; arr):nums(arr) {  
    for (int i = 0; i &lt; nums.size(); ++i) m[nums[i]].push_back(i);    
  }

  int query(int left, int right, int threshold) {    
    for (int i = 0; i &lt; 30; ++i) {
      int n = nums[rand() % (right - left + 1) + left];
      const auto&amp; idx = m[n];
      int count = upper_bound(begin(idx), end(idx), right) - lower_bound(begin(idx), end(idx), left);
      if (count &gt;= threshold) return n;
    }
    return -1;
  }
private:
  unordered_map&lt;int, vector&lt;int&gt;&gt; m; // num -&gt; {indices}  
  const vector&lt;int&gt;&amp; nums;
};</pre>
</div></div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/algorithms/array/leetcode-1157-online-majority-element-in-subarray/">花花酱 LeetCode 1157. Online Majority Element In 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-1157-online-majority-element-in-subarray/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 303. Range Sum Query &#8211; Immutable</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-303-range-sum-query-immutable/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-303-range-sum-query-immutable/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Fri, 17 Aug 2018 08:00:04 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[prefix sum]]></category>
		<category><![CDATA[range query]]></category>
		<guid isPermaLink="false">https://zxi.mytechroad.com/blog/?p=3563</guid>

					<description><![CDATA[<p>Problem Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0,&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-303-range-sum-query-immutable/">花花酱 LeetCode 303. Range Sum Query &#8211; Immutable</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/awS9dn_XCmI?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<h1><strong>Problem</strong></h1>
<p>Given an integer array <i>nums</i>, find the sum of the elements between indices <i>i</i> and <i>j</i> (<i>i</i> ≤ <i>j</i>), inclusive.</p>
<p><b>Example:</b></p>
<pre class="crayon:false">Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -&gt; 1
sumRange(2, 5) -&gt; -1
sumRange(0, 5) -&gt; -3
</pre>
<p><b>Note:</b></p>
<ol>
<li>You may assume that the array does not change.</li>
<li>There are many calls to <i>sumRange</i> function.</li>
</ol>
<h1><strong>Solution: Prefix sum</strong></h1>
<p>sums[i] = nums[0] + nums[1] + &#8230; + nums[i]</p>
<p>sumRange(i, j) = sums[j] &#8211; sums[i &#8211; 1]</p>
<p>Time complexity: pre-compute: O(n), query: O(1)</p>
<p>Space complexity: O(n)</p><pre class="crayon-plain-tag">// Author: Huahua
// Running time: 112 ms
class NumArray {
public:
  NumArray(vector&lt;int&gt; nums): sums_(nums) {      
    if (nums.empty()) return;            
    for (int i = 1; i &lt; nums.size();++i)
      sums_[i] += sums_[i - 1];
  }

  int sumRange(int i, int j) {
    if (i == 0) return sums_[j];
    return sums_[j] - sums_[i-1];
  }
private:    
  vector&lt;int&gt; sums_;
};</pre><p>&nbsp;</p>
<p>&nbsp;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-303-range-sum-query-immutable/">花花酱 LeetCode 303. Range Sum Query &#8211; Immutable</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-303-range-sum-query-immutable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>花花酱 LeetCode 304. Range Sum Query 2D &#8211; Immutable</title>
		<link>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-304-range-sum-query-2d-immutable/</link>
					<comments>https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-304-range-sum-query-2d-immutable/#respond</comments>
		
		<dc:creator><![CDATA[zxi]]></dc:creator>
		<pubDate>Tue, 19 Sep 2017 05:14:44 +0000</pubDate>
				<category><![CDATA[Dynamic Programming]]></category>
		<category><![CDATA[dp]]></category>
		<category><![CDATA[range query]]></category>
		<category><![CDATA[sum]]></category>
		<guid isPermaLink="false">http://zxi.mytechroad.com/blog/?p=348</guid>

					<description><![CDATA[<p>&#160; https://leetcode.com/problems/range-sum-query-2d-immutable/description/ Problem: Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower&#8230;</p>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-304-range-sum-query-2d-immutable/">花花酱 LeetCode 304. Range Sum Query 2D &#8211; Immutable</a> appeared first on <a rel="nofollow" href="https://zxi.mytechroad.com/blog">Huahua&#039;s Tech Road</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><iframe width="500" height="375" src="https://www.youtube.com/embed/MSNSqU3BnXk?feature=oembed" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe></p>
<p>&nbsp;</p>
<p><a href="https://leetcode.com/problems/range-sum-query-2d-immutable/description/">https://leetcode.com/problems/range-sum-query-2d-immutable/description/</a></p>
<p><strong>Problem:</strong></p>
<div class="question-description">
<p>Given a 2D matrix <i>matrix</i>, find the sum of the elements inside the rectangle defined by its upper left corner (<i>row</i>1, <i>col</i>1) and lower right corner (<i>row</i>2, <i>col</i>2).</p>
<p><img src="https://leetcode.com/static/images/courses/range_sum_query_2d.png" alt="Range Sum Query 2D" border="0" /><br />
<small>The above rectangle (with the red border) is defined by (row1, col1) = <b>(2, 1)</b> and (row2, col2) = <b>(4, 3)</b>, which contains sum = <b>8</b>.</small></p>
<p><b>Example:</b></p><pre class="crayon-plain-tag">Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) : 8
sumRegion(1, 1, 2, 2) : 11
sumRegion(1, 2, 2, 4) : 12</pre><p><b>Note:</b></p>
<ol>
<li>You may assume that the matrix does not change.</li>
<li>There are many calls to <i>sumRegion</i> function.</li>
<li>You may assume that <i>row</i>1 ≤ <i>row</i>2 and <i>col</i>1 ≤ <i>col</i>2.</li>
</ol>
</div>
<div id="interviewed-div"><strong>Idea:</strong></div>
<div></div>
<div>Dynamic programming</div>
<div></div>
<div>Time complexity:</div>
<div>O(n^2)</div>
<div>sumRegion: O(1)</div>
<div></div>
<div><a href="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1.png"><img class="alignnone size-full wp-image-353" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-1-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></a><img class="alignnone size-full wp-image-352" style="font-size: 1rem;" src="http://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-2.png" alt="" width="960" height="540" srcset="https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-2.png 960w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-2-300x169.png 300w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-2-768x432.png 768w, https://zxi.mytechroad.com/blog/wp-content/uploads/2017/09/304-ep63-2-624x351.png 624w" sizes="(max-width: 960px) 100vw, 960px" /></div>
<div></div>
<div><strong>Solution:</strong></div>
<p><script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><br />
<ins class="adsbygoogle" style="display: block; text-align: center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-2404451723245401" data-ad-slot="7983117522"></ins><br />
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script></p>
<div>
<pre class="crayon-plain-tag">// Author: Huahua
// Time complexity: 
// constructor: O(n^2)
// sumRegion: O(1)
// Running time: 22 ms 9/2017
class NumMatrix {
public:
    NumMatrix(const vector&lt;vector&lt;int&gt;&gt;&amp; matrix) {
        sums_.clear();
        
        if (matrix.empty()) return;
        
        int m = matrix.size();        
        int n = matrix[0].size();
        
        // sums_[i][j] = sum(matrix[0][0] ~ matrix[i-1][j-1])
        sums_ = vector&lt;vector&lt;int&gt;&gt;(m + 1, vector&lt;int&gt;(n + 1, 0));
        for (int i = 1; i &lt;= m; ++i)
            for (int j = 1; j &lt;= n; ++j)
                sums_[i][j] = matrix[i - 1][j - 1]
                            + sums_[i - 1][j]
                            + sums_[i][j - 1]
                            - sums_[i - 1][j - 1];
    }
    
    int sumRegion(int row1, int col1, int row2, int col2) {        
        return sums_[row2 + 1][col2 + 1]
             - sums_[row2 + 1][col1]
             - sums_[row1][col2 + 1]
             + sums_[row1][col1];
    }
private:
    vector&lt;vector&lt;int&gt;&gt; sums_;
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix obj = new NumMatrix(matrix);
 * int param_1 = obj.sumRegion(row1,col1,row2,col2);
 */</pre><br />
&nbsp;</p>
</div>
<p>The post <a rel="nofollow" href="https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-304-range-sum-query-2d-immutable/">花花酱 LeetCode 304. Range Sum Query 2D &#8211; Immutable</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-304-range-sum-query-2d-immutable/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
