资讯专栏INFORMATION COLUMN

leetcode 643 Maximum Average Subarray I

SwordFly / 3345人阅读

摘要:题目详情输入一个数组和一个整数。要求找出输入数组中长度为的子数组,并且要求子数组元素的加和平均值最大。

题目详情
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. 

输入一个数组nums和一个整数k。要求找出输入数组中长度为k的子数组,并且要求子数组元素的加和平均值最大。返回这个最大的平均值。

Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: 最大平均值 (12-5-6+50)/4 = 51/4 = 12.75

思路

建立一个长度为k的滑动窗口(即一个长度为k的子数组),然后每次右移一位,并将当前的平均值和存储的最大平均值比较,保留更大的那个值即可。

解法
    public double findMaxAverage(int[] nums, int k) {
        double curr = 0;
        double max = 0;       
        
        for(int i=0;i max) ? curr : max ;
            
        }
        
        
        return max/k;
        
    }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68418.html

相关文章

  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • Leetcode[152] Maximum Product Subarray

    摘要:复杂度思路要保留一个到某一位来看的最大值和最小值。因为在数组中有负数的出现,所以到这一位为止的能得到的最大值,可能是由之前的最大值和这个数相乘得到,也可能是最小值和这个数相乘得到的。 Leetcode[152] Maximum Product Subarray Find the contiguous subarray within an array (containing at le...

    _ipo 评论0 收藏0
  • [Leetcode] Maximum Subarray 子序列最大和

    摘要:最新更新请见原题链接动态规划复杂度时间空间思路这是一道非常典型的动态规划题,为了求整个字符串最大的子序列和,我们将先求较小的字符串的最大子序列和。而最大子序列和的算法和上个解法还是一样的。 Maximum Subarray 最新更新请见:https://yanjia.me/zh/2019/02/... Find the contiguous subarray within an ar...

    summerpxy 评论0 收藏0
  • [LeetCode] Maximum Size Subarray Sum Equals k

    Problem Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isnt one, return 0 instead. Note The sum of the entire nums array is guaranteed to fit ...

    MudOnTire 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<