MaximumAverageSubarrayI [source code]
public class MaximumAverageSubarrayI {
static
/******************************************************************************/
public class Solution {
public double findMaxAverage(int[] nums, int k) {
int n = nums.length;
int sum = 0;
for (int i = 0; i < k; i++) sum += nums[i];
if (n <= k) return (double) sum / k;
int maxSum = sum;
for (int i = 1; i < n - k + 1; i++) {
sum += nums[i + k - 1] - nums[i - 1];
if (sum > maxSum) maxSum = sum;
}
return (double) maxSum / k;
}
}
/******************************************************************************/
public static void main(String[] args) {
MaximumAverageSubarrayI.Solution tester = new MaximumAverageSubarrayI.Solution();
}
}
这题总是想用sliding window那种思路来做, 不过刚开始不要想那么多, 先用笨办法做.
好像也没有什么特别的东西了, 最后的速度是18(100), 毕竟是新题目, 这个速度不好做参考;
editorial也没有什么更好的答案. discussion也是没有什么帖子.
Problem 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].
Difficulty:Easy
Total Accepted:1.7K
Total Submissions:4.4K
Contributor: Stomach_ache
Companies
google
Related Topics
array
Similar Questions
Maximum Average Subarray II