File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments