Skip to content

643. Maximum Average Subarray I 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  double findMaxAverage(vector<int>& nums, int k) {
    double sum = accumulate(nums.begin(), nums.begin() + k, 0);
    double ans = sum;

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

    return ans / k;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public double findMaxAverage(int[] nums, int k) {
    double sum = 0;
    for (int i = 0; i < k; ++i)
      sum += nums[i];
    double ans = sum;

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

    return ans / k;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findMaxAverage(self, nums: list[int], k: int) -> float:
    summ = sum(nums[:k])
    ans = summ

    for i in range(k, len(nums)):
      summ += nums[i] - nums[i - k]
      ans = max(ans, summ)

    return ans / k