LeetCode Maximum Average Subarray I

LeetCode Maximum Average Subarray I

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的子数组的最大平均数是多少。简单题,因为平均数等于和除以k,k相同,也就相当于求长度为k的最长连续子串的和。

解法是维护一个长度为k的滑动窗口,求滑动窗口内的最大连续子数组的和,然后除以k。

代码如下:

class Solution {
public:
	double findMaxAverage(vector<int>& nums, int k) {
		int n = nums.size();
		if (n < k)return 0;
		int i = 0, sum = 0, ans = INT_MIN;
		for (int j = 0; j < k; ++j)sum += nums[j];
		for (int j = k; j < n; ++j) {
			ans = max(ans, sum);
			sum += nums[j] - nums[i];
			++i;
		}
		ans = max(ans, sum);
		return ans / double(k);
	}
};

本代码提交AC,用时176MS。

Leave a Reply

Your email address will not be published. Required fields are marked *