 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
For example, if the input to the function is
Input
const arr = [1, 12, -5, -6, 50, 3]; const num = 4;
Output
const output = 12.75;
Output Explanation
Because the desired subarray is [12, -5, -6, 50]
Example
Following is the code −
const arr = [1, 12, -5, -6, 50, 3]; const num = 4; const maxAverage = (arr = [], num) => {    let sum = arr.slice(0, num).reduce((acc, v) => acc + v, 0)    let max = sum    for (let i = 1; i <= arr.length - num; i++) {       sum = sum + arr[i + num - 1] - arr[i - 1]       max = Math.max(max, sum)    }    return max / num } console.log(maxAverage(arr, num)); Output
12.75
Advertisements
 