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 sum
3 let sum = 0
4 for (let i = 0; i < k; i++) {
5 sum += nums[i]
6 }
7
8 // slide window
9 let max = sum
10 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 / k
16}

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.

Next Post

LeetCode: Relative Ranks

Sometimes, LeetCode difficulty is not reliable

Previous Post

LeetCode: Keyboard Row

Duck-typing make this problem less hard to implement

HoningJS

Search Posts