LeetCode 643. 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 <=
k<=n<= 30,000. - Elements of the given array will be in the range [-10,000, 10,000].
题解:
维护长度为k的sliding window的最大sum.
Note: In Java, Double.MIN_VALUE is the smallest positive double value, thus here use -Double.MAX_VALUE.
Time Complexity: O(nums.length). Space: O(1).
AC Java:
1 class Solution { 2 public double findMaxAverage(int[] nums, int k) { 3 double res = -Double.MAX_VALUE; 4 double sum = 0; 5 for(int i = 0; i < nums.length; i++){ 6 sum += nums[i]; 7 if(i >= k - 1){ 8 res = Math.max(res, sum / k); 9 sum -= nums[i - k + 1]; 10 } 11 } 12 13 return res; 14 } 15 }
浙公网安备 33010602011771号