Leetcode刷题83-643. 子数组最大平均数 I(C++详细解法!!!)

Come from : [https://leetcode-cn.com/problems/maximum-average-subarray-i/]

643. Maximum Average Subarray I

  • 1.Question
  • 2.Answer
  • 3.大神们的解决方案
  • 4.我的收获

1.Question

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].

2.Answer

easy 类型题目。
我的暴力解题思路
依次求出 K 个元素的 平均值,找出最大的即可,但是 超出时间限制。。。

超时代码如下:(比较low。。。)

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

3.大神们的解决方案

动态规划,滑动窗解法。
AC代码如下:

class Solution {
     
public:
    double findMaxAverage(vector<int>& nums, int k) {
     
        int maxAvg = INT_MIN;
        int sumK = 0;
        for(int i = 0; i < k; ++i)  //整个最大和  初始化为前k个数最大和
        {
        
            sumK += nums[i];
        }
        if(sumK > maxAvg)
        {
     
            maxAvg = sumK;
        }
        for(int i = k; i < nums.size(); ++i)
        {
     
            sumK = sumK + nums[i] - nums[i - k];// 减去第一个加上最后一个
            
            if(sumK > maxAvg)  //         maxAvg = max(maxAvg, sumK);
            {
     
                 maxAvg = sumK;   // 取最大值
            }

        }
        return (double)maxAvg/k;
    }
};

4.我的收获

Fighting~~~

2019/5/20 胡云层 于南京 83

你可能感兴趣的:(LeetCode从零开始,LeetCode,C++)