Skip to content

Commit 1da34f6

Browse files
committed
Add solution #643
1 parent a916632 commit 1da34f6

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@
218218
606|[Construct String from Binary Tree](./0606-construct-string-from-binary-tree.js)|Easy|
219219
617|[Merge Two Binary Trees](./0617-merge-two-binary-trees.js)|Easy|
220220
628|[Maximum Product of Three Numbers](./0628-maximum-product-of-three-numbers.js)|Easy|
221+
643|[Maximum Average Subarray I](./0643-maximum-average-subarray-i.js)|Easy|
221222
645|[Set Mismatch](./0645-set-mismatch.js)|Medium|
222223
648|[Replace Words](./0648-replace-words.js)|Medium|
223224
653|[Two Sum IV - Input is a BST](./0653-two-sum-iv-input-is-a-bst.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* 643. Maximum Average Subarray I
3+
* https://leetcode.com/problems/maximum-average-subarray-i/
4+
* Difficulty: Easy
5+
*
6+
* You are given an integer array nums consisting of n elements, and an integer k.
7+
*
8+
* Find a contiguous subarray whose length is equal to k that has the maximum average
9+
* value and return this value. Any answer with a calculation error less than 10-5
10+
* will be accepted.
11+
*/
12+
13+
/**
14+
* @param {number[]} nums
15+
* @param {number} k
16+
* @return {number}
17+
*/
18+
var findMaxAverage = function(nums, k) {
19+
let sum = 0;
20+
for (let i = 0; i < k; i++) {
21+
sum += nums[i];
22+
}
23+
24+
let max = sum;
25+
for (let i = k; i < nums.length; i++) {
26+
sum = sum - nums[i - k] + nums[i];
27+
max = Math.max(max, sum);
28+
}
29+
30+
return max / k;
31+
};

0 commit comments

Comments
 (0)