# 643. Maximum Average Subarray I

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MhTM4VP1ia8zn0VDqcr%2F-MhTMCm6lOFnydwdU0z6%2Fimage.png?alt=media\&token=8d5bfd00-cb5e-4464-8310-43c44da72bca)

sliding window

time: O(n)

space: O(1)

```java
class Solution {
    public double findMaxAverage(int[] nums, int k) {
        // sliding window, find the maximum sum
        double sum = 0;
        for (int i = 0; i < k; i++) {
            sum += nums[i];
        }
        double res = sum;
        for (int i = k; i < nums.length; i++) {
            sum += nums[i] - nums[i-k];
            res = Math.max(res, sum);
        }
        return res/k;
    }
}
```
