Leetcode 643. Maximum Average Subarray I

291 篇文章 2 订阅
146 篇文章 0 订阅

Problem

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 1 0 − 5 10^{-5} 105 will be accepted.

Algorithm

First get the sum of the first item and save in sums, then get the k elements sum with sumk[i] = sums[i+k]-sums[i].

Code

class Solution:
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        nlen = len(nums)
        sums = [0] * (nlen+1)
        for i in range(1, nlen+1):
            sums[i] = sums[i-1] + nums[i-1]
        
        sumk = [0] * (nlen - k + 1)
        for i in range(nlen - k + 1):
            sumk[i] = (sums[k+i] - sums[i]) / k

        return max(sumk)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值