Short Python & C++


  • 0
    Z

    python solution:

    class Solution(object):
        def findMaxAverage(self, nums, k):
            maxsum = ksum = sum(itertools.islice(nums, 0, k))
            for i in xrange(k, len(nums)):
                ksum += nums[i] - nums[i-k]
                maxsum = max(maxsum, ksum)
            return maxsum / float(k)
    

    c++ solution:

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

Log in to reply
 

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