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

 

這道題給了我們一個數組nums,還有一個數字k,讓我們找長度為k且平均值最大的子數組。由於子數組必須是連續的,所以我們不能給數組排序。那么怎么辦呢,在博主印象中,計算子數組之和的常用方法應該是建立累加數組,然后我們可以快速計算出任意一個長度為k的子數組,用來更新結果res,從而得到最大的那個,參見代碼如下:

 

解法一:

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int n = nums.size();
        vector<int> sums = nums;
        for (int i = 1; i < n; ++i) {
            sums[i] = sums[i - 1] + nums[i];
        }
        double mx = sums[k - 1];
        for (int i = k; i < n; ++i) {
            mx = max(mx, (double)sums[i] - sums[i - k]);
        }
        return mx / k;
    }
};

 

由於這道題子數組的長度k是確定的,所以我們其實沒有必要建立整個累加數組,而是先算出前k個數字的和,然后就像維護一個滑動窗口一樣,將窗口向右移動一位,即加上一個右邊的數字,減去一個左邊的數字,就等同於加上右邊數字減去左邊數字的差值,然后每次更新結果res即可,參見代碼如下:

 

解法二:

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

 

參考資料:

https://discuss.leetcode.com/topic/96134/c-simple-sliding-window-solution

https://discuss.leetcode.com/topic/96154/java-solution-sum-of-sliding-window

 

LeetCode All in One 題目講解匯總(持續更新中...) 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM