Maximum of all Subarrays of Size k using JavaScript

Last Updated : 10 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This problem is about finding the biggest number in all groups of k adjacent numbers in an array. In JavaScript, you'd go through the array, looking at each group of k numbers at a time, and picking out the biggest one. This task is pretty common and is useful for things like analyzing data or optimizing processes in JavaScript programming.

Input: Array[]= [1, 3, 5, 2, 4, 6, 8], K=3

Output: [5, 5,5,6, 8]

Explanation:
Subarray [1, 3, 5]: Maximum value is 5.
Subarray [3, 5, 2]: Maximum value is 5.
Subarray [5, 2, 4]: Maximum value is 5.
Subarray [2, 4, 6]: Maximum value is 6.
Subarray [4, 6, 8]: Maximum value is 8.

Below are the approaches to maximize all the subarrays of size K using JavaScript:

Sliding Window Approach

  • Start by initializing two pointers, let's call them 'left' and 'right', both pointing to the beginning of the array.
  • Move the 'right' pointer to the right until the size of the window (distance between 'left' and 'right' pointers) becomes k.
  • At each step, keep track of the maximum value within the current window.
  • Once the window size reaches k, record the maximum value.
  • Move the window by incrementing the 'left' pointer and 'right' pointer simultaneously.
  • Repeat steps 2-5 until the 'right' pointer reaches the end of the array.
  • Return the recorded maximum values for each window.

Example: To demonstrate maximizing all the sub arrays of size k using the sliding window approach in JavaScript.

JavaScript
function maxSubarrays(arr, k) {
    const result = [];
    const window = [];

    const addElement = (index) => {
        while (window
            .length > 0 && arr[index] >= arr[window[window.length - 1]]) {
            window.pop();
        }
        window.push(index);
    };
    const removeElement = (index) => {
        if (window.length > 0 && window[0] === index) {
            window.shift();
        }
    };

    for (let i = 0; i < k; i++) {
        addElement(i);
    }
    for (let i = k; i < arr.length; i++) {
        result.push(arr[window[0]]);
        removeElement(i - k);
        addElement(i);
    }
    result.push(arr[window[0]]);
    return result;
}

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const k = 3;
console.log(maxSubarrays(array, k)); 

Output
[
  3, 4, 5,  6,
  7, 8, 9, 10
]

Time Complexity: O(n)

Auxiliary Space: O(k)

Max-Heap Approach

The approach of using a max heap to find the maximum of all subarrays involves maintaining a heap data structure where the maximum element in the current window of size k is always at the root of the heap. As the window slides through the array, we remove the elements that are no longer in the window and add the new elements that are now in the window. This approach ensures that we always have the maximum element readily available.

  • Initialize an empty max heap.
  • Iterate through the array from index 0 to n - 1, where n is the length of the array.
  • For each element encountered, add it to the heap.
  • If the size of the heap exceeds k, remove the element that is no longer in the window.
  • If the size of the heap equals k, the maximum element in the current window is at the root of the heap. Add this maximum to the result array.
  • Repeat steps 3 to 5 until all elements in the array are processed.

Example: To demonstrate maximizing all subarrays of size k using max-heap approach in JavaScript.

JavaScript
function maxSubArray(arr, k) {
    const result = [];
    const maxHeap = [];

    for (let i = 0; i < arr.length; i++) {
        maxHeap.push(arr[i]);


        if (maxHeap.length > k) {
            maxHeap.shift();
        }

        if (maxHeap.length === k) {
            // Find the maximum value in the current
            // window and add it to the result
            result.push(Math.max(...maxHeap));
        }
    }

    return result;
}

// Example usage:
const arr = [1, 3, 5, 2, 4, 6, 8];
const k = 3;
console.log(maxSubArray(arr, k));

Output
[ 5, 5, 5, 6, 8 ]

Time Complexity : O(n * log(k))

Auxiliary Space Complexity : O(k)

Maximum of all subarrays of size K using Set

Using a set approach involves maintaining a set data structure to keep track of the elements in the current window of size k. As the window slides through the array, we remove elements that are no longer in the window and add new elements that are now in the window. This approach allows us to efficiently determine the maximum element in each window without the need for sorting or heap operations.

  • Initialize an empty set to store elements in the current window.
  • Initialize two pointers: left and right, both starting at 0.
  • Iterate through the array from index 0 to n - 1, where n is the length of the array.
  • For each element encountered, add it to the set.
  • If the size of the set exceeds k, remove the element that is no longer in the window.
  • If the window size equals k, determine the maximum element in the window and add it to the result array.
  • Increment both left and right pointers and repeat steps 4 to 6 until right pointer reaches the end of the array.

Example: To demonstrate maximizing all subarrays of size k using set in JavaScript.

JavaScript
function maxSubArray(arr, k) {
    const result = [];
    const windowSet = new Set();

    let left = 0;
    let right = 0;
    while (right < arr.length) {
        windowSet.add(arr[right]);
        if (right - left + 1 > k) {
            windowSet.delete(arr[left]);
            left++;
        }
        if (right - left + 1 === k) {
            result.push(Math.max(...windowSet));
        }

        right++;
    }

    return result;
}

const arr = [1, 3, 5, 2, 4, 6, 8];
const k = 3;
console.log(maxSubArray(arr, k)); 

Output
[ 5, 5, 5, 6, 8 ]

Time Complexity: O(n)

Auxiliary Space Complexity: O(k)


Next Article

Similar Reads