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

 


题目标签:Array

  题目给了我们一个nums array 和一个 k,让我们找到长度为k 的子数组,它的平均值是最大的。

  这题比较容易想到的方法就是 sliding window, 想象一下有一个长度为k 的窗口在移动,每次加上一个新的num,还要减去一个旧的num。维护更新一个最大的sum。(这里不需要在每一次维护更新的时候 / k,最后 /k 就可以了)  

  最后用最大的sum / k 。

  

  在做这一题的过程中,我发现 Double.MIN_VALUE 居然是大于0的数字。之前用的 Integer.MIN_VALUE 明明是最小的负数。

  来看一下Double.MIN_VALUE 的定义:A constant holding the smallest positive nonzero value of type double, 2-1074.

 

 

Java Solution:

Runtime beats 51.30% 

完成日期:10/19/2017

关键词:Array

关键点:Sliding Window

 1 class Solution 
 2 {
 3     public double findMaxAverage(int[] nums, int k) 
 4     {
 5         double mav = -Double.MAX_VALUE;
 6         double tempMav = 0;
 7         
 8         for(int i=0; i<nums.length; i++)
 9         {
10             tempMav += nums[i];
11             
12             if(i + 1 >= k)
13             {   
14                 mav = Math.max(mav, tempMav);
15                 tempMav -= nums[i + 1 - k];
16             }
17              
18         }
19         
20        
21         return mav / k;
22     }
23 }

参考资料:N/A

 

LeetCode 题目列表 - LeetCode Questions List

 

posted @ 2017-10-20 01:54  Jimmy_Cheng  阅读(217)  评论(0编辑  收藏  举报