LeetCode Maximum Average Subarray I

原题链接在这里:https://leetcode.com/problems/maximum-average-subarray-i/description/

题目:

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75

Note:

  1. 1 <= k <= n <= 30,000.
  2. Elements of the given array will be in the range [-10,000, 10,000].

题解:

维护长度为k的sliding window的最大sum.

Time Complexity: O(nums.length). Space: O(1).

AC Java:

 1 class Solution {
 2     public double findMaxAverage(int[] nums, int k) {
 3         if(nums == null || nums.length < k){
 4             throw new IllegalArgumentException("Illegal input array length smaller than k.");
 5         }
 6         
 7         long sum = 0;
 8         for(int i = 0; i<k; i++){
 9             sum += nums[i];
10         }
11         
12         long max = sum;
13         for(int i = k; i<nums.length; i++){
14             sum += nums[i]-nums[i-k];
15             max = Math.max(max, sum);
16         }
17         return max*1.0/k;
18     }
19 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7542513.html