美文网首页Leetcode
Leetcode 643. Maximum Average Su

Leetcode 643. Maximum Average Su

作者: SnailTyan | 来源:发表于2018-09-14 21:33 被阅读1次

    文章作者:Tyan
    博客:noahsnail.com  |  CSDN  |  简书

    1. Description

    Maximum Average Subarray I

    2. Solution

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

    Reference

    1. https://leetcode.com/problems/maximum-average-subarray-i/description/

    相关文章

      网友评论

        本文标题:Leetcode 643. Maximum Average Su

        本文链接:https://www.haomeiwen.com/subject/xvzogftx.html