643.Maximum Average Subarray I Posted on 2017-09-13 | In LeetCode Solution 1: accepted 22msIteration.Time: O(n)Space: O(1) 12345678910111213141516public double findMaxAverage(int[] nums, int k) { int len = nums.length; if (len < k) return 0; double sum = 0; for(int i = 0; i < k; i++) { sum += nums[i] / (double) k; } double max = sum; for(int i = 1; i < len - k + 1; i++) { sum = sum - nums[i-1] / (double) k + nums[i+k-1] / (double) k; max = Math.max(max, sum); } return max; } Solution 2: accepted 19msCalculate the average at last - be flexible man. 12345678910111213141516public double findMaxAverage(int[] nums, int k) { int len = nums.length; if (len < k) return 0; double sum = 0; for(int i = 0; i < k; i++) { sum += nums[i]; } double max = sum; for(int i = 1; i < len - k + 1; i++) { sum = sum - nums[i - 1] + nums[i + k - 1]; max = Math.max(max, sum); } return max / (double) k; }