# LeetCode: Maximum Average Subarray I Solution

Find maximum sum of contiguous subarray with length of K

## Approach: Sliding window

Init a sum of contiguous subarray of

[0, k]

On every next slide, add the current iterated number and subtract the previous begin range

For example, sum of

[1, k + 1]
will be
sum([0, k]) - nums[0] + nums[k + 1]

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var findMaxAverage = function (nums, k) {2  // init sum3  let sum = 04  for (let i = 0; i < k; i++) {5    sum += nums[i]6  }7
8  // slide window9  let max = sum10  for (let i = k; i < nums.length; i++) {11    sum = sum + nums[i] - nums[i - k]12    max = Math.max(max, sum)13  }14
15  return max / k16}```

leetcode

array

sliding window

## Next Post

LeetCode: Relative Ranks

Sep 10, 2021

Sometimes, LeetCode difficulty is not reliable

## Previous Post

LeetCode: Keyboard Row

Sep 8, 2021

Duck-typing make this problem less hard to implement

Search Posts