
Sponsored
Sponsored
This approach involves checking each possible window (of length k) one by one and calculating the maximum for each window. This method is straightforward but inefficient for large arrays as it runs in O(n*k) time complexity.
Time complexity: O(n*k), where n is the number of elements.
Space complexity: O(1) for storing the maximum of each window in output array.
1function maxSlidingWindow(nums, k) {
2 const result = [];
3 for (let i = 0; i <= nums.length - k; i++) {
4 let max = -Infinity;
5 for (let j = i; j < i + k; j++) {
6 max = Math.max(max, nums[j]);
7 }
8 result.push(max);
9 }
10 return result;
11}
12
13// Example usage:
14const nums = [1, 3, -1, -3, 5, 3, 6, 7];
15const k = 3;
16console.log(maxSlidingWindow(nums, k));The JavaScript solution follows a similar nested loop approach to find the maximum element within each sliding window and pushes the result to an array.
Use a deque (double-ended queue) to store indices of array elements, which helps in maintaining the maximum for the sliding window in an efficient manner. As the window slides, the method checks and rearranges the deque so that the front always contains the index of the maximum element.
Time complexity: O(n), where n is the number of elements.
Space complexity: O(k) for the deque.
1
This C program uses a circular array-based deque to store indices. The deque is created such that the maximum element's index is always at the front and other elements are stored in a way that elements outside the window or smaller than the current maximum are removed efficiently.