LeetCode Maximum Average Subarray I
Posted Dylan_Java_NYC
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 <=
k
<=n
<= 30,000. - 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 }
以上是关于LeetCode Maximum Average Subarray I的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Maximum Average Subarray I
[leetcode-644-Maximum Average Subarray II]
leetCode-Maximum Average Subarray I
[leetcode-643-Maximum Average Subarray I]