-
Notifications
You must be signed in to change notification settings - Fork 4
/
Solution.js
59 lines (51 loc) · 1.19 KB
/
Solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(nums, k) {
var length = nums.length - k + 1, i, ans = Number.NEGATIVE_INFINITY, sum, j;
for (i = 0; i < length; i++) {
sum = 0;
for (j = i; j < k + i; j++) {
sum += nums[j];
}
if (ans < sum / k) ans = sum / k;
}
return ans;
};
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(nums, k) {
var length = nums.length, sum = [], ans;
for (i = 0; i < length; i++) {
if (i === 0) sum[i] = nums[i];
else sum[i] = sum[i - 1] + nums[i];
}
ans = sum[k - 1] / k;
for (i = k; i < length; i++) {
ans = Math.max(ans, (sum[i] - sum[i - k]) / k);
}
return ans;
};
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var findMaxAverage = function(nums, k) {
var length = nums.length, i, sum = 0, ans;
for (i = 0; i < k; i++) {
sum += nums[i];
}
ans = sum;
for (i = k; i < length; i++) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
}
ans /= k;
return ans;
};