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.

Idea 1. Brute force, use the idea on maximum subarray(Leetcode 53), for any pairs (i, j), j - i >= k-1, 0 <= i  <= j < nums.length, check whether the sum of nums[i..j] is greater than the maximum sum so far.

Time complexity: O(n2)

Space complexity: O(1)

public class Solution {
public double findMaxAverage(int[] nums, int k) {
double maxAverage = Integer.MIN_VALUE; for(int i = 0; i < nums.length; ++i) {
double sum = 0;
for(int j = i; j < nums.length; ++j) {
sum += nums[j];
if(j-i + 1 >= k) {
maxAverage = Math.max(maxAverage, sum/(j-i+1));
}
}
} return maxAverage;
}
}

Idea 1.a Brute force, use the idea on Maximum Average Subarray I (Leetcode 643). Linearly find all the maximum average subarray for subarray length >= k.

public class Solution {
public double findMaxAverageWithLengthK(int[] nums, int k) {
double sum = 0;
for(int i = 0; i < k; ++i) {
sum += nums[i];
} double maxSum = sum;
for(int i = k; i < nums.length; ++i) {
sum = sum + nums[i] - nums[i-k];
maxSum = Math.max(maxSum, sum);
} return maxSum/k;
}
public double findMaxAverage(int[] nums, int k) {
double maxAverage = Integer.MIN_VALUE; for(int i = k; i < nums.length; ++i) {
double average = findMaxAverageWithLengthK(nums, i);
maxAverage = Math.max(maxAverage, average);
} return maxAverage;
}
}

Idea 2. Smart idea, use two techniques

1. Use binary search to guess the maxAverage, minValue in the array <= maxAverage <= maxValue in the array, assumed the guesed maxAverage is mid, if there exists a subarray with length >= k whos average is bigger than mid, then the maxAverage must be located between [mid, maxValue], otherwise between [minValue, mid].

2. How to efficiently check if there exists a subarray with length >= k whos average is bigger than mid? do you still remember the cumulative sum in maximum subArray? maximum sum subarray with length >= k can be computed by cumu[j] - min(cumu[i]) where j - i + 1 >= 0. If we deduct each element with mid (nums[i] -mid), the problem is transfered to find if there exists a subarray whoes sum >= 0. Since this is not strictly to find the maxSum, in better case if any subarray's sum >= 0, we terminate the search early and return true; in worst case we search all the subarray and find the maxmum sum, then check if maxSum >= 0.

Time complexity: O(nlogn)

Space complexity: O(1)

public class Solution {
private boolean containsAverageArray(List<Integer> nums, double targetAverage, int k) {
double sum = 0;
for(int i = 0; i < k; ++i) {
sum += nums.get(i) - targetAverage;
} if(sum >= 0) return true; double previousSum = 0;
double minPreviousSum = 0;
double maxSum = -Double.MAX_VALUE;
for(int i = k; i < nums.size(); ++i) {
sum += nums.get(i) - targetAverage;
previousSum += nums.get(i-k) - targetAverage;
minPreviousSum = Math.min(minPreviousSum, previousSum);
maxSum = Math.max(maxSum, sum - minPreviousSum);
if (maxSum >= 0) {
return true;
}
} return false;
} public double findMaxAverage(List<Integer> nums, int k) { double minItem = Collections.min(nums);
double maxItem = Collections.max(nums); while(maxItem - minItem >= 1e-5 ) {
double mid = minItem + (maxItem - minItem)/2.0; boolean contains = containsAverageArray(nums, mid, k);
if (contains) {
minItem = mid;
}
else {
maxItem = mid;
} } return maxItem;
}
}

We can reduce one variable, maxSum, terminate if sum - minPrevious >= 0, sum - minPreviousSum is the maxSum ended at current index.

a. sum - minPrevious < 0 if maxSum > sum - minPrevious,  maxSum < 0 in previous check

b. sum - minPrevious < 0 if maxSum < sum -minPrevious < 0

c. sum - minPrevious > 0 if maxSum < 0 < sum - minPrevious

public class Solution {
private boolean containsAverageArray(List<Integer> nums, double targetAverage, int k) {
double sum = 0; for(int i = 0; i < k; ++i) {
sum += nums.get(i) - targetAverage;
}
if(sum >= 0) return true; double previousSum = 0;
double minPreviousSum = 0;
for(int i = k; i < nums.size(); ++i) {
sum += nums.get(i) - targetAverage;
previousSum += nums.get(i-k) - targetAverage;
minPreviousSum = Math.min(minPreviousSum, previousSum);
if(sum >= minPreviousSum ) {
return true;
}
} return false;
} public double findMaxAverage(List<Integer> nums, int k) { double minItem = Collections.min(nums);
double maxItem = Collections.max(nums); while(maxItem - minItem >= 1e-5 ) {
double mid = minItem + (maxItem - minItem)/2.0; boolean contains = containsAverageArray(nums, mid, k);
if (contains) {
minItem = mid;
}
else {
maxItem = mid;
} } return maxItem;
} }

Idea 3. There is a O(n) solution listed on this paper section 3 (To read maybe)
https://arxiv.org/pdf/cs/0311020.pdf

Maximum Average Subarray II LT644的更多相关文章

  1. leetcode644. Maximum Average Subarray II

    leetcode644. Maximum Average Subarray II 题意: 给定由n个整数组成的数组,找到长度大于或等于k的连续子阵列,其具有最大平均值.您需要输出最大平均值. 思路: ...

  2. [LeetCode] Maximum Average Subarray II 子数组的最大平均值之二

    Given an array consisting of n integers, find the contiguous subarray whose length is greater than o ...

  3. [LeetCode] 644. Maximum Average Subarray II 子数组的最大平均值之二

    Given an array consisting of n integers, find the contiguous subarray whose length is greater than o ...

  4. Maximum Average Subarray II

    Description Given an array with positive and negative numbers, find the maximum average subarray whi ...

  5. LC 644. Maximum Average Subarray II 【lock,hard】

    Given an array consisting of n integers, find the contiguous subarray whose length is greater than o ...

  6. 643. Maximum Average Subarray I 最大子数组的平均值

    [抄题]: Given an array consisting of n integers, find the contiguous subarray of given length k that h ...

  7. LeetCode 643. 子数组最大平均数 I(Maximum Average Subarray I)

    643. 子数组最大平均数 I 643. Maximum Average Subarray I 题目描述 给定 n 个整数,找出平均数最大且长度为 k 的连续子数组,并输出该最大平均数. LeetCo ...

  8. Maximum Average Subarray

    Given an array with positive and negative numbers, find the maximum average subarray which length sh ...

  9. 【Leetcode_easy】643. Maximum Average Subarray I

    problem 643. Maximum Average Subarray I 题意:一定长度的子数组的最大平均值. solution1:计算子数组之后的常用方法是建立累加数组,然后再计算任意一定长度 ...

随机推荐

  1. iostat磁盘监控工具

    安装iostat磁盘监控工具 1.安装 yum install sysstat 2.运行 iostat -k -d -x 1 10 -k:以kb为单位统计 -d:显示磁盘状态 -x:显示详细信息 1: ...

  2. 解决不联网无法启动struts2问题

    Unable to load configuration. - Class: java.net.PlainSocketImplFile: PlainSocketImpl.javaMethod: con ...

  3. python学习day6 for循环 字符串的内置方法

    1.for循环 和while相比 l=[1,2,3] i=0 while i <len(l) print(l[i]) i+=1 l=['a','b','c'] for item in l: pr ...

  4. 1、list 的一些相关操作 2、增删改查 3、tuple 的操作 4、range

    1. list(增删改查) 列表可以装大量的数据. 不限制数据类型. 表示方式:[] 方括号中的每一项用逗号隔开 列表和字符串一样.也有索引和切片 # lst = [1, "周杰伦" ...

  5. POJ-3126.PrimePath(欧拉筛素数打表 + BFS)

    给出一篇有关素数线性筛和区间筛的博客,有兴趣的读者可以自取. 本题大意: 给定两个四位的素数,没有前导零,每次变换其中的一位,最终使得两个素数相等,输出最小变换次数.要求变换过程中的数也都是素数. 本 ...

  6. TOJ 2130: Permutation Recovery(思维+vector的使用)

    传送门:http://acm.tzc.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=2130 时间限制(普通/Java): ...

  7. Handler Runnable 自动执行 循环 连续 延时

    这是一种可以创建多线程消息的函数使用方法:1,首先创建一个Handler对象 Handler handler=new Handler(); 2,然后创建一个Runnable对象Runnable run ...

  8. ds.Tables[0].Rows.RemoveAt(i)数据库表格删除行

    不要在循环里使用myDataTable.Rows.RemoveAt(i).因为每删除一行后.i的值会增加,但行数会是减少了.这么做一定会出错.因此要遍历数据,使用Remove方式时,要倒序的遍历int ...

  9. unity缓动插件DOTween Pro v0.9.680

    DoTween Pro是一款unity插件,是unity中最好用的tween插件,比起Dotween的免费版要多很多功能,实现脚本和视觉脚本的新功能,支持包括移动,淡出,颜色,旋转,缩放,打孔,摇动, ...

  10. GridView中CheckBox单击事件(oncheckedchanged)

    在GridView中加入 CheckBox控件,想通过单击选中出现如下图所示效果: 具体做法是: 前台GV部份省掉.只加关键的CheckBox部份. view plaincopy to clipboa ...