Leetcode 643 Solution

This article provides solution to leetcode question 643 (maximum-average-subarray-i)

https://leetcode.com/problems/maximum-average-subarray-i

Solution

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int sum = 0;

        for (int i = 0; i < k; i++)
            sum += nums[i];
        int ans = sum;

        for (int i = k, j = 0; i < nums.size(); i++, j++)
        {
            sum += nums[i] - nums[j];
            ans = max(sum, ans);
        }

        return ans * 1.0 / k;
    }
};