当前位置:网站首页>Force buckle 643 Subarray maximum average I

Force buckle 643 Subarray maximum average I

2022-07-07 20:06:00 Tomorrowave

643. Maximum average of subarrays I

Here you are n An integer array of elements nums And an integer k .

Please find the largest average and The length is k A continuous subarray of , And output the maximum average .

Any error less than 10-5 All answers will be considered correct .

Example 1:

Input :nums = [1,12,-5,-6,50,3], k = 4
Output :12.75
explain : Maximum average (12-5-6+50)/4 = 51/4 = 12.75

Example 2:

Input :nums = [5], k = 1
Output :5.00000

Tips :

n == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104

Ideas :

The sliding window : First define a window to move from left to right , When the length does not meet k, The window keeps →, When , Satisfy k when , The window determines whether the maximum value is the current maximum value , If meet , Continue to move right , If the length exceeds k Then shorten the window

Code

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        i,j= 0,-1
        sumls=0
        maxval=-10000000
        while j<len(nums)-1 :
            j+=1
            sumls+=nums[j]
            while j - i + 1 > k:
                sumls -= nums[i]
                i+=1
            if j - i + 1 == k :
                maxval=max(maxval,sumls)
        return maxval/k
原网站

版权声明
本文为[Tomorrowave]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071753355392.html