Easy python solution


  • 0
    Z
    class Solution(object):
        def findMaxAverage(self, nums, k):
            """
            :type nums: List[int]
            :type k: int
            :rtype: float
            """
            sum_k = 0
            for i in range(k):
                sum_k += nums[i]
            ave_max = sum_k*1.0/k
            next_ind = k
            while next_ind < len(nums):
                sum_k = sum_k + nums[next_ind]-nums[next_ind-k]
                ave_max = max(sum_k*1.0/k,ave_max)
                next_ind += 1
            
            return ave_max

  • 0
    Z
    and C++ version
    
    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            int start = 0;
            int sum_k = 0;
            double max_avg;
            for (int i=0;i<k;i++){
                sum_k+=nums[i];
            }
            max_avg = sum_k*1.0/k;
            for (int i=k; i<nums.size(); i++){
                sum_k += nums[i]-nums[start];
                start++;
                max_avg = max(max_avg,sum_k*1.0/k);
            }
            return max_avg;
            
        }
    };

Log in to reply
 

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