Skip to content

Commit 45f5fb1

Browse files
committed
feat: Solving Maximum Average Subarray (LeetCode | #643 | Easy)
1 parent 025408d commit 45f5fb1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

sliding-window/max-avg-subarray.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* LeetCode | #643 | Easy
3+
*
4+
* You are given an integer array nums consisting of n elements, and an integer k.
5+
* Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value.
6+
* Any answer with a calculation error less than 10-5 will be accepted.
7+
*
8+
* Constraints:
9+
* 1. n == nums.length
10+
* 2. 1 <= k <= n <= 10^5
11+
* 3. -10^4 <= nums[i] <= 10^4
12+
*
13+
*/
14+
15+
/**
16+
* Time complexity: O(n) - Space complexity: O(1)
17+
*
18+
* @param {number[]} nums
19+
* @param {number} k
20+
* @return {number}
21+
*/
22+
function findMaxAverage(nums, k) {
23+
let maxAvg;
24+
let subarraySum = 0;
25+
for (let i = 0; i < k; i++) {
26+
subarraySum += nums[i];
27+
}
28+
maxAvg = subarraySum / k;
29+
30+
for (let i = 1; i + k <= nums.length; i++) {
31+
subarraySum += nums[i - 1] * -1 + nums[i + k - 1];
32+
const subarrayAvg = subarraySum / k;
33+
34+
if (subarrayAvg > maxAvg) {
35+
maxAvg = subarrayAvg;
36+
}
37+
}
38+
39+
return maxAvg;
40+
};
41+

0 commit comments

Comments
 (0)