美文网首页
643. Maximum Average Subarray I

643. Maximum Average Subarray I

作者: morningstarwang | 来源:发表于2021-02-04 11:11 被阅读0次

    Ref: https://leetcode-cn.com/problems/maximum-average-subarray-i/

    这道题思路比较清晰,滑动窗口,维持窗口的sum,每次减去滑动前第一个元素,加上滑动后最后一个元素,代码实现如下:

    class Solution:
       def findMaxAverage(self, nums: List[int], k: int) -> float:
    
           m_sum = sum(nums[:k])
           result = m_sum
           for i, j in zip(nums[:-k], nums[k:]):
               m_sum -= i
               m_sum += j
               if m_sum > result:
                   result = m_sum
           return result / k
    

    相关文章

      网友评论

          本文标题:643. Maximum Average Subarray I

          本文链接:https://www.haomeiwen.com/subject/mbqbtltx.html