[LeetCode] Maximum Average Subarray I

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Maximum Average Subarray I相关的知识,希望对你有一定的参考价值。

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. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

给定一个由n个整数组成的数组,计算数组中相邻连续k个元素的最大平均值。按照题意使用了两层for循环计算结果,但是提交时显示超时。

技术分享
class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double res = -INT_MAX;
        for (int i = 0; i != nums.size() - k + 1; i++) {
            double sum = 0;
            for (int j = i; j != i + k; j++) 
                sum += nums[j];
            res = max(res, sum);
        }
        
        return res / k;
    }
};
// TLE
TLE Code

分析原因得到2层for循环导致超时,经过思考采用一个for循环来进行计算,每次计算到k的整数和时判断该和是否为最大值,接着把最k个数中第一个减去,再在后面添加一个整数。类似于滑动一个长度为k的窗口,代码如下

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

 

 

以上是关于[LeetCode] Maximum Average Subarray I的主要内容,如果未能解决你的问题,请参考以下文章

#Leetcode# 53. Maximum Subarray

LeetCode 53. Maximum Subarray

LeetCode -- Maximum Product Subarray

leetcode 53. Maximum Subarray

LeetCode Third Maximum Number

LeetCode Create Maximum Number