題目詳情
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<nums.length;i++){if(i < k){curr = curr + nums[i];max = curr;continue;}curr = curr + nums[i] - nums[i-k]; max = (curr > max) ? curr : max ;}return max/k;}