Skip to content

Commit dde341f

Browse files
authored
Create 643. Maximum Average Subarray I.py
1 parent e7cd9d8 commit dde341f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def findMaxAverage(self, nums, k):
3+
"""
4+
:type nums: List[int]
5+
:type k: int
6+
:rtype: float
7+
Note:
8+
1 <= k <= n <= 30,000.
9+
Elements of the given array will be in the range [-10,000, 10,000].
10+
sliding window
11+
to determine the sum of elements from the index i+1 to the index i+k+1,
12+
all we need to do is to subtract the element nums[i]from x and to add the element nums[i+k+1]to x.
13+
"""
14+
answer = -10000 * len(nums)
15+
total = 0
16+
17+
for i in range(len(nums)):
18+
total += nums[i]
19+
if i >= k:
20+
total -= nums[i - k]
21+
if i >= k -1:
22+
answer = max(answer, total / k)
23+
24+
return answer
25+

0 commit comments

Comments
 (0)