Leetcode之Maximum Average Subarray I

问题描述:

Given an array consisting of n integers, find the contiguous subarray of given lengthk that has the maximum average value. And you need to output the maximum average value.

示例:

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].

问题来源:Maximum Average Subarray I (详细地址:https://leetcode.com/problems/maximum-average-subarray-i/description/)

思路分析:这道题其实是个求和的题目,只是换了个求平均数的说法而已,这道题相比最大连续子数组的题(Maximum Subarray)还是要简单些的,在这只需要维持一个大小为4的滑动窗口就好了,关键是如何维持呢?标准是什么呢?标准就是:如果当前的这个元素加进去组成的值比之前的四个元素的和要大,我们就抛弃最前面的那个数,听上去怎么那么残忍呢?没办法,谁让你不够大呢?

代码:

Leetcode之Maximum Average Subarray I_第1张图片









你可能感兴趣的:(leetcode,java,leetcode,面试,算法)