[Leetcode]643.Maximum Average Subarray I

链接:LeetCode643

给定\(n\)个整数,找出平均数最大且长度为$ k $的连续子数组,并输出该最大平均数。

示例 1:

输入: \([1,12,-5,-6,50,3]\), k = 4
输出: 12.75
解释: 最大平均数 (12-5-6+50)/4 = 51/4 = 12.75

相关标签:滑动窗口

重点在于构造滑动窗口,以\(k\)为窗口大小往后滑动,注意判空即可。代码如下:

python:

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        if not nums:
            return 0
        cur = res = sum(nums[:k])
        start = 0
        for end in range(k,len(nums)):
            cur += -nums[start]+nums[end]
            start += 1
            res = max(cur,res)
        return res/k

C++:

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        if(nums.empty()){
            return 0;
        }
        double start,cur,res;
        start  = cur = res = 0;
        for(int i = 0;i<k;i++){
            cur += nums[i];
        }
        res = cur;
        for(int i=k;i<nums.size();i++){
            cur += nums[i]-nums[start];
            start += 1;
            res = max(res,cur);
        }
        return res/k;
    }
};
posted @ 2020-01-18 22:10  Jamest  阅读(117)  评论(0编辑  收藏  举报