[leetcode]643. Maximum Average Subarray I

[leetcode]643. Maximum Average Subarray I


Analysis

准备尝试黑咖啡~—— [孩怕~]

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.
用滑动窗口解决~

Implement

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int len = nums.size();
        int res;
        int sum = 0;
        for(int i=0; i<k; i++)
            sum += nums[i];
        res = sum;
        for(int i=k; i<len; i++){
            sum += (nums[i] - nums[i-k]);
            res = max(res, sum);
        }
        return (double)res/k;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/81051091