Maximum average of a specific length of subarray in JavaScript

JavascriptWeb DevelopmentFront End Technology

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 −

 Live Demo

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
raja
Published on 24-Apr-2021 10:33:58
Advertisements