C++ solution : sliding window method.


  • 0
    T
    /* Sliding window
     * using sumK to record current K sum, foward 1 step every circulation. For example:
     * 1st: sumK = nums[0] + nums[1] + ... + nums[k - 1]
     * 2nd: sumK = nums[1] + nums[2] + ... + nums[k]
     * ...
     * using maxK to record the bigger one of current sumK and next sumK.
     */
    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            double maxK = 0;
            double sumK = 0;
            
            for (int i = 0; i < k; i++) {
                sumK += nums[i];
            }
            
            maxK = sumK;  // 1st sumK
            
            for (int i = k; i < nums.size(); i++) {
                sumK = sumK + nums[i] - nums[i - k];  // next sumK
                maxK = max(maxK, sumK);
            }
            
            return maxK / k;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.