leetcode-643. 子数组最大平均数 I

643. 子数组最大平均数 I - 力扣(Leetcode)

滑动窗口,判断好边界条件即可

func findMaxAverage(nums []int, k int) float64 {
    begin, end := 0, k-1
    if end >= len(nums) {
        end = len(nums) - 1
    }

    curSum := 0
    for i := begin; i <= end; i++ {
        curSum += nums[i]
    }

    maxAvg := float64(curSum) / float64(end - begin + 1)

    end++
    for ; end < len(nums); end++ {
        // fmt.Println(begin, end)
        curSum += nums[end]
        curSum -= nums[begin]

        avg := float64(curSum) / float64(end - begin)
        if avg > maxAvg {
            maxAvg = avg
        }

        begin++
    }

    return maxAvg
}
posted @ 2023-01-03 23:25  吴丹阳-V  阅读(24)  评论(0编辑  收藏  举报