leetcode643-- Maximum Average Subarray I

# 小郑之家~

### 题目

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].



### 解答


class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""

window = nums[:k]
maxm = sum(window)
temp = maxm
for i in range(k, len(nums)):
temp = temp -nums[i-k]+nums[i]

maxm = max(temp, maxm)

return maxm*1.0/k


class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""

sums = []
sums[:] = nums

for i in range(1, len(nums)):
sums[i] = sums[i-1] + nums[i]

mx = sums[k-1]

for i in range(k, len(nums)):
mx = max(mx, sums[i]-sums[i-k])

return 1.0*mx/k