Maximum of all Subarrays of Size k using JavaScript
Last Updated :
10 May, 2024
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));
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));
Time Complexity: O(n)
Auxiliary Space Complexity: O(k)
Similar Reads
Sliding Window Maximum using JavaScript
Given an array of integers and a window size, the task is to find the maximum element in each window of the array as it slides from left to right. Below are the approaches to solve the Sliding Window Maximum problem using JavaScript: Table of Content Brute Force ApproachOptimal ApproachBrute Force A
2 min read
Length of the Longest Subarray with Zero Sum using JavaScript
JavaScript allows us to find the longest subarray with zero-sum. We have to return the length of the longest subarray whose sum is equal to zero. There are several approaches in JavaScript to achieve this which are as follows: Table of Content Using Nested loop (Brute force Approach)Using map object
3 min read
Max Length of Subarray with Given Sum Limit in JavaScript Array
Given an array, our task is to find the maximum length of a subarray whose sum does not exceed a given value. We can use different approaches like the Brute Force Approach and the Sliding Window Approach to find the maximum length of a subarray. Below are the approaches to find the maximum length of
3 min read
First Element to Occur K Times using JavaScript
Given an array and number, our task is to find the first element that occurs exactly k times in an array using JavaScript. Example: Input: array= [1, 2, 3, 4, 2, 5, 6, 4, 2] and k = 3.Output: 2Explanation: Here the first element that occurred 3 times in the array is 2Table of Content Using nested fo
3 min read
JavaScript Program to Find Largest Subarray with a Sum Divisible by k
Finding the largest subarray with a sum divisible by a given integer 'k' is a common problem in JavaScript and other programming languages. This task involves identifying a contiguous subarray within an array of integers such that the sum of its elements is divisible by 'k' and is as long as possibl
5 min read
JavaScript Program for K-th Largest Sum Contiguous Subarray
In this article, we are going to learn about K-th Largest Sum Contiguous Subarray in JavaScript. K-th Largest Sum Contiguous Subarray refers to finding the K-th largest sum among all possible contiguous subarrays within a given array of numbers, It involves exploring different subarray lengths and p
7 min read
JavaScript Program to Find Maximum of Minimum for Every Window Size in a Given Array
Given an array of integers, find the maximum of minimums for every window size in the array. The window size varies from 1 to the size of the array. Example: Input: Array: [1, 2, 3, 5, 1, 7, 3]Output: [7, 3, 2, 1, 1, 1, 1]Explanation: The first element in the output indicates the maximum of minimums
4 min read
Longest Subarray with Sum Divisible by Given Number in Array with JavaScript
Given an array of integers, the task is to find the longest subarray whose sum is divisible by a given number. Example: Input: [4, 5, 0, -2, -3, 1], k = 5Output: Length = 6Below are the approaches to find the longest subarray with sum divisible by a given number using JavaScript: Table of Content Br
3 min read
JavaScript Program to Find Top k Elements
Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest). Table
4 min read
JavaScript Program to find Maximum Distance Between two Occurrences of Same Element in Array
Given an array of repeated elements, the task is to find the maximum distance between two occurrences of an element.Example:Input : arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}Output: 10// maximum distance for 2 is 11-1 = 10 // maximum distance for 1 is 4-2 = 2 // maximum distance for 4 is 10-5 = 5
4 min read