--- title: 'LeetCode 643. Maximum Average Subarray I' disqus: hackmd --- # LeetCode 643. Maximum Average Subarray I ## Description 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 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 Input: nums = [5], k = 1 Output: 5.00000 ## Constraints n == nums.length 1 <= k <= n <= 10^5^ -10^4^ <= nums[i] <= 10^4^ ## Answer 此題可直接用一個for做疊加,算到k-1項後就可以加入max的判斷,接下來的計算除了跌加之外還要減掉num[i-k]項,如此才能算是k個項相加,最後return時再取平均即可。 ```Cin= //2022_03_13 double findMaxAverage(int* nums, int numsSize, int k){ double ans = 0, max = *nums; for(int i = 1; i<numsSize; i++){ nums[i] += nums[i-1]; if(i >= k-1){ if(i == k-1){max = nums[i];} else{ ans = nums[i] - nums[i-k]; max = max > ans ? max : ans; } } } return max/k; } ``` ## Link https://leetcode.com/problems/maximum-average-subarray-i/ ###### tags: `Leetcode`