diff --git a/maximumSubarray b/maximumSubarray new file mode 100644 index 0000000..1589828 --- /dev/null +++ b/maximumSubarray @@ -0,0 +1,27 @@ + //Function to find maximum of each subarray of size k. + vector max_of_subarrays(int *arr, int n, int k) + { + // your code here + deque dq; + vector res; + + for(int i = 0; i < k; ++i) { + while(!dq.empty() and arr[dq.back()] <= arr[i]) dq.pop_back(); + dq.push_back(i); + } + + + for(int i = k; i < n; ++i) { + res.push_back(arr[dq.front()]); + + while(!dq.empty() and dq.front() <= i-k) dq.pop_front(); + + while(!dq.empty() and arr[dq.back()] <= arr[i]) dq.pop_back(); + + dq.push_back(i); + } + + res.push_back(arr[dq.front()]); + + return res; + }