smj007

maxiumum average subarray I

Apr 24th, 2025
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.87 KB | None | 0 0
  1. class Solution:
  2.     def findMaxAverage(self, nums: List[int], k: int) -> float:
  3.        
  4.         left = 0
  5.         right = 0
  6.         window_sum = 0
  7.         max_window_sum = -float("inf")
  8.        
  9.         while right < len(nums):
  10.             if nums[right] < k - 1:
  11.                 # keep adding until you expanded the
  12.                 # window enough
  13.                 window_sum = window_sum + nums[right]
  14.                 right += 1
  15.             else:
  16.                 # add right most element assuming that left most
  17.                 # element is already inside the window
  18.                 window_sum = window_sum + nums[right]
  19.                 max_window_sum = max(window_sum, max_window_sum)
  20.  
  21.                 # prepare for next iteration
  22.                 window_sum -= nums[left]
  23.                 left += 1
  24.                 right += 1
  25.  
  26.         return max_window_sum/(k*1.0)
  27.  
Advertisement
Add Comment
Please, Sign In to add comment