Leetcode 643. Maximum Average Subarray I 最大平均区间 解题报告

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MebiuW/article/details/75734888

1 前言

回归了,语言不定,可能是Python(新的题目),也可能是Java(旧的题目),形式可能会更加简单了,就这样,有空再说

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Note:
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

就是找出一个给定区间值平均值最大的,似乎没什么难度吧。。

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """

        res = sum(nums[0:k]) 
        tmp = res
        n = len(nums)
        for i in range(k,n):
            tmp = tmp - nums[i -k] + nums[i]
            res = max(res, tmp)

        return res / ( k + 0.0)

猜你喜欢

转载自blog.csdn.net/MebiuW/article/details/75734888