呓语Beta 2.0 首页 镜头后 灶台前 捐赠者名单 有趣的小站

leetcode 643 Maximum Average Subarray I

文档信息

leetcode 643 Maximum Average Subarray I

解法一 TLE

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        ans = sum(nums[:k]) / float(k)
        
        for i in range(len(nums)-k+1):
            ans = max(ans, sum(nums[i:i+k])/float(k))
        
        return ans

解法二

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        ans = s = sum(nums[:k])
        
        for i in range(1, len(nums)-k+1):
            s = s - nums[i-1] + nums[i+k-1]
            ans = max(ans, s)
        
        return ans / float(k)

note

捐赠支持

可以使用支付宝转帐给richard.ma.19850509#gmail.com(请将#替换为@),谢谢!

Fork me on GitHub