code.ashish.me

Atom feed

Recently added: 02 Count Of Subset Sum, 416 Partition Equal Subset Sum, 01 Subset Sum, 518 Coin Change 2, 983 Minimum Cost For Tickets

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