{"id":27393,"date":"2018-02-02T21:12:47","date_gmt":"2018-02-02T15:42:47","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27393"},"modified":"2018-02-02T21:12:47","modified_gmt":"2018-02-02T15:42:47","slug":"cc-programming-maximum-of-all-subarrays-of-size-k","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/cc-programming-maximum-of-all-subarrays-of-size-k\/","title":{"rendered":"C\/C++ Programming-Maximum of all sub arrays of size k"},"content":{"rendered":"<p>Given an array and an integer k, find the maximum for each and every contiguous subarray of size k.<span id=\"more-11306\"><\/span><\/p>\n<p>Examples:<\/p>\n<p>Input :<br \/>\narr[] = {1, 2, 3, 1, 4, 5, 2, 3, 6}<br \/>\nk = 3<br \/>\nOutput :<br \/>\n3 3 4 5 5 5 6<\/p>\n<p>Input :<br \/>\narr[] = {8, 5, 10, 7, 9, 4, 15, 12, 90, 13}<br \/>\nk = 4<br \/>\nOutput :<br \/>\n10 10 10 15 15 90 90<\/p>\n<div id=\"practice\">\u00a0<strong>Method 1 (Simple)<\/strong><br \/>\nRun two loops. In the outer loop, take all subarrays of size k. In the inner loop, get the maximum of the current subarray<\/div>\n<div><\/div>\n<div><strong>C Programming<\/strong><\/div>\n<div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include&lt;stdio.h&gt;<br\/> <br\/>void printKMax(int arr[], int n, int k)<br\/>{<br\/>    int j, max;<br\/> <br\/>    for (int i = 0; i &lt;= n-k; i++)<br\/>    {<br\/>        max = arr[i];<br\/> <br\/>        for (j = 1; j &lt; k; j++)<br\/>        {<br\/>            if (arr[i+j] &gt; max)<br\/>               max = arr[i+j];<br\/>        }<br\/>        printf(&quot;%d &quot;, max);<br\/>    }<br\/>}<br\/> <br\/> <br\/>int main()<br\/>{<br\/>    int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    int k = 3;<br\/>    printKMax(arr, n, k);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: The outer loop runs n-k+1 times and the inner loop runs k times for every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written as O(nk).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 (Use Self-Balancing BST)<\/strong><br \/>\n1) Pick first k elements and create a Self-Balancing Binary Search Tree (BST) of size k.<br \/>\n2) Run a loop for i = 0 to n \u2013 k<br \/>\na) Get the maximum element from the BST, and print it.<br \/>\nb) Search for arr[i] in the BST and delete it from the BST.<br \/>\nc) Insert arr[i+k] into the BST.<\/p>\n<p>Time Complexity: Time Complexity of step 1 is O(kLogk). Time Complexity of steps 2(a), 2(b) and 2(c) is O(Logk). Since steps 2(a), 2(b) and 2(c) are in a loop that runs n-k+1 times, time complexity of the complete algorithm is O(kLogk + (n-k+1)*Logk) which can also be written as O(nLogk).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 3 (A O(n) method: use Dequeue)<\/strong><br \/>\nWe create a <a href=\"http:\/\/en.wikipedia.org\/wiki\/Double-ended_queue\" target=\"_blank\" rel=\"noopener noreferrer\">Dequeue<\/a>, <em>Qi <\/em>of capacity k, that stores only useful elements of current window of k elements. An element is useful if it is in current window and is greater than all other elements on left side of it in current window. We process all array elements one by one and maintain <em>Qi <\/em>to contain useful elements of current window and these useful elements are maintained in sorted order. The element at front of the <em>Qi <\/em>is the largest and element at rear of <em>Qi <\/em>is the smallest of current window.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Following is C++ implementation of this method.<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">#include &lt;iostream&gt;<br\/>#include &lt;deque&gt;<br\/> <br\/>using namespace std;<br\/> <br\/>\/\/ A Dequeue (Double ended queue) based method for printing maixmum element of<br\/>\/\/ all subarrays of size k<br\/>void printKMax(int arr[], int n, int k)<br\/>{<br\/>    \/\/ Create a Double Ended Queue, Qi that will store indexes of array elements<br\/>    \/\/ The queue will store indexes of useful elements in every window and it will<br\/>    \/\/ maintain decreasing order of values from front to rear in Qi, i.e., <br\/>    \/\/ arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order<br\/>    std::deque&lt;int&gt;  Qi(k);<br\/> <br\/>    \/* Process first k (or first window) elements of array *\/<br\/>    int i;<br\/>    for (i = 0; i &lt; k; ++i)<br\/>    {<br\/>        \/\/ For very element, the previous smaller elements are useless so<br\/>        \/\/ remove them from Qi<br\/>        while ( (!Qi.empty()) &amp;&amp; arr[i] &gt;= arr[Qi.back()])<br\/>            Qi.pop_back();  \/\/ Remove from rear<br\/> <br\/>        \/\/ Add new element at rear of queue<br\/>        Qi.push_back(i);<br\/>    }<br\/> <br\/>    \/\/ Process rest of the elements, i.e., from arr[k] to arr[n-1]<br\/>    for ( ; i &lt; n; ++i)<br\/>    {<br\/>        \/\/ The element at the front of the queue is the largest element of<br\/>        \/\/ previous window, so print it<br\/>        cout &lt;&lt; arr[Qi.front()] &lt;&lt; &quot; &quot;;<br\/> <br\/>        \/\/ Remove the elements which are out of this window<br\/>        while ( (!Qi.empty()) &amp;&amp; Qi.front() &lt;= i - k)<br\/>            Qi.pop_front();  \/\/ Remove from front of queue<br\/> <br\/>        \/\/ Remove all elements smaller than the currently<br\/>        \/\/ being added element (remove useless elements)<br\/>        while ( (!Qi.empty()) &amp;&amp; arr[i] &gt;= arr[Qi.back()])<br\/>            Qi.pop_back();<br\/> <br\/>         \/\/ Add current element at the rear of Qi<br\/>        Qi.push_back(i);<br\/>    }<br\/> <br\/>    \/\/ Print the maximum element of last window<br\/>    cout &lt;&lt; arr[Qi.front()];<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    int arr[] = {12, 1, 78, 90, 57, 89, 56};<br\/>    int n = sizeof(arr)\/sizeof(arr[0]);<br\/>    int k = 3;<br\/>    printKMax(arr, n, k);<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>78 90 90 90 89<\/pre>\n<p>Time Complexity: O(n). It seems more than O(n) at first look. If we take a closer look, we can observe that every element of array is added and removed at most once. So there are total 2n operations.<br \/>\nAuxiliary Space: O(k)<\/p>\n[ad type=&#8221;banner&#8221;]\n<div id=\"company_tags\"><\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>C\/C++ Programming Maximum of all sub arrays of size k Given an array and an integer k, find the maximum for each and every contiguous sub array of size k.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69866,1,73012,80124],"tags":[81630,81623,81626,83872,83874,83873,81625,83875],"class_list":["post-27393","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-data-structures","category-queue","tag-find-maximum-of-minimum-for-every-window-size-in-a-given-array","tag-maximum-of-all-subarrays-of-size-k-java","tag-maximum-sum-of-all-subarrays-of-size-k","tag-reverse-array-in-groups","tag-sliding-window-maximum","tag-sliding-window-maximum-maximum-of-all-subarrays-of-size-k","tag-sliding-window-maximum-java","tag-sliding-window-maximum-python"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27393","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27393"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27393\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27393"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27393"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27393"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}