Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Maximum Average Subarray I

$
0
0

题目描述:

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 = 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 will be in the range [-10,000, 10,000].

题目大意:

给定包含n个整数的数组,寻找长度为k的连续子数组的平均值的最大值。

解题思路:

滑动窗口(Sliding Window)

Python代码:

class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        ans = None
        sums = 0
        for x in range(len(nums)):
            sums += nums[x]
            if x >= k: sums -= nums[x - k]
            if x >= k - 1: ans = max(ans, 1.0 * sums / k)
        return ans

 


Viewing all articles
Browse latest Browse all 559

Latest Images

Trending Articles



Latest Images