# 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

1var findMaxAverage = function (nums, k) {2 // init sum3 let sum = 04 for (let i = 0; i < k; i++) {5 sum += nums[i]6 }78 // 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 }1415 return max / k16}

## Comments

Loading comments...

## Tags

leetcode

array

sliding window

## Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

**Fact corner:** Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

**Still hesitate?** Read HoningJS author's guide on dealing with Toptal interview process.