Leetcode——643. Maximum Average Subarray I

xiaoxiao2021-02-28  7

题目原址

https://leetcode.com/problems/maximum-average-subarray-i/description/

题目描述

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. Example1:

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 <= k <= n <= 30,000.

解题思路

减少循环次数,因为只需要循环到nums.length-k次就可以了内层循环,累加连续的k个数,累加和赋值给临时变量ver,判断返回值与ver的大小,保证返回值最大。每次循环,不要忘记把ver的值变为0

AC代码

class Solution { public double findMaxAverage(int[] nums, int k) { double result = Double.NEGATIVE_INFINITY; int loop = nums.length - k; for(int i = 0; i <= loop; i++) { int ver = 0; for(int j = i; j < i + k; j++) { ver += nums[j]; } result = result < ver ? ver : result; } result /= k; return result; } }
转载请注明原文地址: https://www.6miu.com/read-2400354.html

最新回复(0)