Two Pointer Style - C++ O(n) time, O(1) space


  • 0
    C
    class Solution {
    public:
        double findMaxAverage(vector<int>& v, int k) {
            int start = 0, end = 0, sum = 0, ret_sum = INT_MIN;
            while(end < v.size()) {
                sum += v[end];
                if(end - start + 1 == k) {
                    ret_sum = max(sum, ret_sum);
                    sum -= v[start++];
                }  
                end++;
            }
            return (double)ret_sum/(double)k;
        }
    };
    

Log in to reply
 

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