Created
March 12, 2023 04:40
-
-
Save pjcodesjs/d9e4c4985c0a1154fccded64b280198f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function maxSubarray(arr, k) { | |
const result = []; // to store maximum values of subarrays | |
const queue = []; // to store indices of elements in the current subarray | |
for (let i = 0; i < arr.length; i++) { | |
// remove elements that are outside of the current window | |
if (queue.length > 0 && queue[0] <= i - k) { | |
queue.shift(); | |
} | |
// remove elements that are smaller than the current element | |
while (queue.length > 0 && arr[i] >= arr[queue[queue.length - 1]]) { | |
queue.pop(); | |
} | |
// add current element to the queue | |
queue.push(i); | |
// add maximum element to the result array if the current window is complete | |
if (i >= k - 1) { | |
result.push(arr[queue[0]]); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment