LintCode 868. Maximum Average Subarray

本文介绍了一种使用滑动窗口算法解决寻找给定长度的最大平均子数组的问题。通过示例说明了如何实现这一算法,包括初始化窗口、遍历数组并更新窗口和最大平均值的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Maximum Average Subarray

Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. You need to output the maximum average value.

Example
Example1

Input: nums = [1,12,-5,-6,50,3] and k = 4
Output: 12.75
Explanation:
Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
Example2

Input: nums = [4,2,1,3,3] and k = 2
Output: 3.00
Explanation:
Maximum average is (3+3)/2 = 6/2 = 3.00
Notice
1 <= k <= n <= 30,000.
Elements of the given array will be in the range [-10,000, 10,000].

思路:滑动窗口。
记得maxResult初值设为numeric_limits::lowest();
要include。

代码如下:

#include <limits>

class Solution {
public:
    /**
     * @param nums: an array
     * @param k: an integer
     * @return: the maximum average value
     */
    double findMaxAverage(vector<int> &nums, int k) {
        int len = nums.size();
        if (len == 0 || len < k) return 0.0;
        
        double result = 0.0;
        double maxResult = numeric_limits<double>::lowest();
        
        double windowSum = 0;
        
        for (int i = 0; i < len; ++i) {
            windowSum += nums[i];
            if (i >= k) windowSum -= nums[i - k];
            maxResult = max(maxResult, windowSum);
        }
        
        return maxResult / k;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值