[Leetcode]643. Maximum Average Subarray I

本文介绍了一种算法,用于在给定长度的连续子数组中找到具有最大平均值的子数组,并详细解释了其实现过程。通过将每K个连续元素视为一个整体并逐步移动,比较这些元素的总和与当前最大总和,从而找到最大平均值。

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

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 = 4
Output: 12.75
Explanation: 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].

 

思路:把数组里每 K 个连续

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        double sum = 0;
        for (int i = 0; i < k; i++)    
            sum += nums[i];
        double max = sum;
        for (int i = 0; i  < nums.length - k; i++){
            sum += nums[i+k] - nums[i];
            max = Math.max(max, sum);
        }
        return max / k;
    }
}

 

元素看作一个整体,然后一步一步地移动,比较这 K 个元素合与当前最大合 max 的大小。

 

转载于:https://www.cnblogs.com/David-Lin/p/7874435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值