code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

05 Maximum Average Subarray 1

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

const maximumAverageSubarray = (nums, k) => {
  let currentSum = 0
  let max = 0
  for (let i = 0; i < k; i++) {
    currentSum += nums[i]
  }
  max = currentSum
  for (let right = 1; right <= nums.length - k; right++) {
    currentSum = currentSum - nums[right - 1] + nums[right + k - 1]
    max = Math.max(currentSum, max)
  }
  return max / k
}

test('maximumAverageSubarray', () => {
  expect(maximumAverageSubarray([1, 12, -5, -6, 50, 3], 4)).toEqual(12.75)
})

Created 2022-02-04T04:03:39+00:00 · Edit