Leetcode 643. Maximum Average Subarray I

Problem

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 1 0 − 5 10^{-5} 105 will be accepted.

Algorithm

First get the sum of the first item and save in sums, then get the k elements sum with sumk[i] = sums[i+k]-sums[i].

Code

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        nlen = len(nums)
        sums = [0] * (nlen+1)
        for i in range(1, nlen+1):
            sums[i] = sums[i-1] + nums[i-1]
        
        sumk = [0] * (nlen - k + 1)
        for i in range(nlen - k + 1):
            sumk[i] = (sums[k+i] - sums[i]) / k

        return max(sumk)

你可能感兴趣的:(Leetcode,解题报告,入门题,leetcode,算法,职场和发展)