Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum average of a specific length of subarray in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of integers, arr, as the first argument and a number, num, as the second argument.
Our function should find the contiguous subarray of given length num that has the maximum average value. And we need to output the maximum average value.
Example Input and Output
For example, if the input to the function is:
const arr = [1, 12, -5, -6, 50, 3]; const num = 4;
The expected output is:
12.75
Output Explanation: The desired subarray is [12, -5, -6, 50] which has sum 51 and average 51/4 = 12.75.
Approach: Sliding Window Technique
The most efficient approach uses the sliding window technique to avoid recalculating sums from scratch:
- Calculate the sum of the first subarray of length num
- Slide the window by removing the leftmost element and adding the new rightmost element
- Track the maximum sum found
- Return the maximum average by dividing by num
Implementation
const arr = [1, 12, -5, -6, 50, 3];
const num = 4;
const maxAverage = (arr = [], num) => {
// Calculate sum of first subarray
let sum = arr.slice(0, num).reduce((acc, v) => acc + v, 0);
let max = sum;
// Slide the window through remaining positions
for (let i = 1; i
12.75
How It Works
Let's trace through the algorithm with our example array [1, 12, -5, -6, 50, 3] and num = 4:
const arr = [1, 12, -5, -6, 50, 3];
const num = 4;
console.log("Initial subarray [1, 12, -5, -6]:");
let sum = arr.slice(0, 4).reduce((acc, v) => acc + v, 0);
console.log("Sum:", sum, "Average:", sum/4);
console.log("\nSliding window:");
for (let i = 1; i
Initial subarray [1, 12, -5, -6]:
Sum: 2 Average: 0.5
Sliding window:
Remove 1, Add 50
Sum: 2 + 50 - 1 = 51
Average: 12.75
Remove 12, Add 3
Sum: 51 + 3 - 12 = 42
Average: 10.5
Time and Space Complexity
| Complexity | Value | Explanation |
|---|---|---|
| Time | O(n) | Single pass through the array |
| Space | O(1) | Only storing sum and max variables |
Edge Cases
// Test with minimum length console.log(maxAverage([1, 2, 3], 1)); // Should return 3 (max element) // Test with array length equal to subarray length console.log(maxAverage([1, 2, 3], 3)); // Should return 2 (average of all elements) // Test with negative numbers console.log(maxAverage([-1, -2, -3, -4], 2)); // Should return -1.5
3 2 -1.5
Conclusion
The sliding window technique efficiently finds the maximum average subarray in O(n) time. This approach avoids redundant calculations by reusing previous sums, making it optimal for this type of problem.
