class Solution(object):
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
sum_k = 0
for i in range(k):
sum_k += nums[i]
ave_max = sum_k*1.0/k
next_ind = k
while next_ind < len(nums):
sum_k = sum_k + nums[next_ind]nums[next_indk]
ave_max = max(sum_k*1.0/k,ave_max)
next_ind += 1
return ave_max
Easy python solution


and C++ version class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int start = 0; int sum_k = 0; double max_avg; for (int i=0;i<k;i++){ sum_k+=nums[i]; } max_avg = sum_k*1.0/k; for (int i=k; i<nums.size(); i++){ sum_k += nums[i]nums[start]; start++; max_avg = max(max_avg,sum_k*1.0/k); } return max_avg; } };