643. Maximum Average Subarray I

Easy题的意义是一定要思维缜密。
比如,nums[]有可能是负数,那max的初值就不能是0;
另外,计算完成后total要置0,要么就把total拿到for里面去。

Brute Force

    public double findMaxAverage(int[] nums, int k) {
        double max = Integer.MIN_VALUE;
        int total = 0;
        for (int i = 0; i < nums.length + 1 - k; i++) {
            for (int count = 0; count < k; count++) {
                total += nums[i + count];
            }
            max = Math.max(max, total / (double) k);
            total = 0 ;
        }
        return max;
    }

Sliding Window

边界条件最好举例子带进去不然会错。

    public double findMaxAverage(int[] nums, int k) {
        //sliding window

        int total = 0;
        for (int i = 0; i < k; i++) {
            total += nums[i];
        }
        double max = total / (double) k;
        for (int i = 1; i < nums.length - k + 1; i++) {
            total = total - nums[i - 1];
            total = total + nums[i + k - 1];
            max = Math.max(total / (double) k, max);
        }
        return max;
    }

另外还有种方法:
Approach #2 Cumulative Sum [Accepted]

你可能感兴趣的:(643. Maximum Average Subarray I)