Maximum Average Subarray II

update Aug 17, 2017 18:55

LeetCodearrow-up-right Lintcodearrow-up-right

Given an array consisting of n integers, find the contiguous subarray whose length is greater than or equal to 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:

when length is 5, maximum average value is 10.8, when length is 6, maximum average value is 9.16667. Thus return 12.75.

Note:

  1. 1 <= k <= n <= 10,000.

  2. Elements of the given array will be in range [-10,000, 10,000].

  3. The answer with the calculation error less than 10-5 will be accepted.

Basic Idea:

因为题目要求是长度不小于k的连续子序列的最大平均值,这个问题直接解的话只能是O(n^2)的时间,需要遍历每个子序列。为了加快速度,我们选择使用对答案进行二分,猜测答案然后验证的算法。

对答案的二分大概会执行最多几十次(因为log2(MAX_INT) = 32),每次验证消耗时间为O(n),所以这种算法最终的时间复杂度为O(n)。

其中,验证一个数组中是否存在长度不小于 k 的子数组平均值不小于 target,我们可以先将原数组减去 target,然后验证是否有长度不小于 k 的子数组的和大于等于 0。后者可以在O(n)的时间内办到。

Java Code:

update Dec 1, 2017 12:58

更新

之前的 Java code 仍然感觉写的很好,尤其是 isValid() 函数。再更新一个Python的解,但是由于 LeetCode 的 OJ 设定问题,对于python的时间too tight,这个 O(c*n) (c 大概为几十) 的解会 TLE: