首页 > 其他分享 >leetcode-643-easy

leetcode-643-easy

时间:2023-01-08 19:57:38浏览次数:40  
标签:nums int leetcode 643 easy Output Example

Maximum Average Subarray I

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 10-5 will be accepted.

Example 1:

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

Input: nums = [5], k = 1
Output: 5.00000
Constraints:

n == nums.length
1 <= k <= n <= 105
-104 <= nums[i] <= 104

思路一:滑动窗口

    public double findMaxAverage(int[] nums, int k) {
        double sum = 0D;
        for (int i = 0; i <= k - 1; i++) {
            sum += nums[i];
        }

        double temp = sum;
        for (int i = 1; i + k - 1 < nums.length; i++) {
            temp = temp - nums[i - 1] + nums[i + k - 1];
            sum = Math.max(sum, temp);
        }

        return sum / k;
    }

标签:nums,int,leetcode,643,easy,Output,Example
From: https://www.cnblogs.com/iyiluo/p/17035188.html

相关文章

  • leetcode-496-easy
    NextGreaterElementIThenextgreaterelementofsomeelementxinanarrayisthefirstgreaterelementthatistotherightofxinthesamearray.Youar......
  • leetcode-521-easy
    LongestUncommonSubsequenceIGiventwostringsaandb,returnthelengthofthelongestuncommonsubsequencebetweenaandb.Ifthelongestuncommonsubseq......
  • leetcode-551-easy
    StudentAttendanceRecordIYouaregivenastringsrepresentinganattendancerecordforastudentwhereeachcharactersignifieswhetherthestudentwasab......
  • leetcode-485-easy
    MaxConsecutiveOnesGivenabinaryarraynums,returnthemaximumnumberofconsecutive1'sinthearray.Example1:Input:nums=[1,1,0,1,1,1]Output:3E......
  • leetcode-434-easy
    NumberofSegmentsinaStringGivenastrings,returnthenumberofsegmentsinthestring.Asegmentisdefinedtobeacontiguoussequenceofnon-spacech......
  • 【LeetCode数组#4】长度最小的子数组
    长度最小的子数组力扣题目链接(opensnewwindow)给定一个含有n个正整数的数组和一个正整数s,找出该数组中满足其和≥s的长度最小的连续子数组,并返回其长度。如......
  • [leetcode每日一题]1.8
    ​​2185.统计包含给定前缀的字符串​​难度简单28给你一个字符串数组 ​​words​​ 和一个字符串 ​​pref​​ 。返回 ​​words​​ 中以 ​​pref​​ 作为 ......
  • 【优先队列】LeetCode 23. 合并K个升序链表
    题目链接23.合并K个升序链表思路把全部结点放入优先队列中,然后再依次组成新链表代码classSolution{publicListNodemergeKLists(ListNode[]lists){......
  • LeetCode 236_二叉树的最近公共祖先
    LeetCode236:二叉树的最近公共祖先题目给定一个二叉树,找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为:“对于有根树T的两个节点p、q,最近......
  • LeetCode 887. 鸡蛋掉落-题解分析
    题目来源887.鸡蛋掉落题目详情给你k枚相同的鸡蛋,并可以使用一栋从第1层到第n层共有n层楼的建筑。已知存在楼层f,满足 0<=f<=n,任何从高于f的楼层落......