Leetcode 643. Maximum Average Subarray I (one of the maximum mean Subarray)

Source: Internet
Author: User

Given an arrays consisting n of integers, find the contiguous subarray of Given length that have the k maximum Avera GE value. And you need to output the maximum average value.

Example 1:

Input: [1,12,-5,-6,50,3], k = 4output:12.75explanation: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 would be in the range [-10,000, 10,000].

Title tag: Array

The topic gives us a nums array and a K, let's find a subarray of length k, its average value is the largest.

The easy way to think of this is to sliding window, imagine that there is a windows with a length of k moving, add a new num each time, and subtract an old num. Maintains a maximum sum of updates. (There is no need for each maintenance update at the time/K, the last/k will be)

Finally, use the biggest sum/k.

  

In the process of doing this problem, I found that double.min_value is actually more than 0 figures. The integer.min_value used before is clearly the smallest negative number.

Take a look at the definition of Double.min_value: A constant holding the smallest positive nonzero VALUE double of type, 2-1074.

Java Solution:

Runtime beats 51.3%

Completion Date: 10/19/2017

Keywords: Array

Key point: Sliding Window

1 classSolution2 {3      Public DoubleFindmaxaverage (int[] Nums,intk)4     {5         DoubleMav =-Double.max_value;6         DoubleTempmav = 0;7         8          for(inti=0; i<nums.length; i++)9         {TenTempmav + =Nums[i]; One              A             if(i + 1 >=k) -             {    -Mav =Math.max (MAV, TEMPMAV); theTempmav-= nums[i + 1-K]; -             } -               -         } +          -         +         returnMAV/K; A     } at}

Reference: N/A

Leetcode List of topics- leetcode Questions List

Leetcode 643. Maximum Average Subarray I (one of the maximum mean Subarray)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.