Skip to content

Commit 4594fb6

Browse files
committed
Add: Exercise 643. Max Average Subarray I
1 parent d817c49 commit 4594fb6

File tree

4 files changed

+88
-0
lines changed

4 files changed

+88
-0
lines changed
+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# 643. Maximum Average Subarray I
2+
You are given an integer array `nums` consisting of `n` elements, and an integer `k`.
3+
4+
Find a contiguous subarray whose length is equal to `k` that has the maximum average value and
5+
return this value. Any answer with a calculation error less than 10^-5 will be accepted.
6+
7+
## Examples
8+
9+
### Example 1:
10+
11+
Input: `nums` = [1,12,-5,-6,50,3], `k` = 4
12+
Output: 12.75000
13+
Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
14+
15+
### Example 2:
16+
17+
Input: `nums` = [5], `k` = 1
18+
Output: 5.00000
19+
20+
## Constraints
21+
22+
- `n == nums.length`
23+
- `1 <= k <= n <= 10^5`
24+
- `-10^4 <= nums[i] <= 10^4`
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var findMaxAverage = function(nums, k) {
7+
// Sliding window approach
8+
let sum = 0
9+
let maxAv = 0
10+
11+
// Calculate the initial sum
12+
for (let i = 0; i < k; i++) {
13+
sum += nums[i]
14+
}
15+
16+
maxAv = sum / k
17+
18+
// Now let's slide the window
19+
for (let i = k; i < nums.length; i++) {
20+
sum = sum - nums[i-k] + nums[i]
21+
const a = sum / k
22+
if (a > maxAv) maxAv = a
23+
}
24+
25+
return maxAv
26+
};
27+
28+
// Use example
29+
var av = findMaxAverage([1,12,-5,-6,50,3], 4)
30+
31+
module.exports = findMaxAverage
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"name": "643-maximum-average-subarray-1",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"start": "node index.js",
8+
"debug": "node --inspect-brk index.js",
9+
"test": "node test.js"
10+
},
11+
"keywords": [],
12+
"author": "",
13+
"license": "ISC"
14+
}
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
const assert = require('assert')
2+
const findMaxAverage = require('./index')
3+
4+
const tests = [
5+
{
6+
nums: [1,12,-5,-6,50,3],
7+
k: 4,
8+
expectedMaxAv: 12.75,
9+
},
10+
{
11+
nums: [5],
12+
k: 1,
13+
expectedMaxAv: 5,
14+
},
15+
]
16+
17+
for (const t of tests) {
18+
assert.strict.deepEqual(findMaxAverage(t.nums, t.k), t.expectedMaxAv)
19+
}

0 commit comments

Comments
 (0)