ZhongKuo0228 / study

0 stars 0 forks source link

643. Maximum Average Subarray I #72

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago
  1. k 個元素的 sliding window,cur_sum = 上一次 cur_sum - 頭 + 新元素
  2. 一路更新 ans 即可
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        l, r, ans = 0, k - 1, sum(nums[:k])
        cur_sum = ans
        l, r = l + 1, r + 1
        while r < len(nums):
            cur_sum = cur_sum - nums[l - 1] + nums[r]
            ans = max(ans, cur_sum)
            l, r = l + 1, r + 1
        return ans / k
fockspaces commented 1 year ago

GPT improve:

  1. 因為 left, right 固定距離 k 元素,因此直接以 i - k, i 來表示雙指針
class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        cur_sum = sum(nums[:k])
        ans = cur_sum
        for i in range(k, len(nums)):
            cur_sum = cur_sum - nums[i - k] + nums[i]
            ans = max(ans, cur_sum)
        return ans / k