当前位置:网站首页>643. Maximum average number of subarrays I

643. Maximum average number of subarrays I

2022-07-01 14:20:00 mrbone9

Address :

Power button icon-default.png?t=M1FBhttps://leetcode-cn.com/problems/maximum-average-subarray-i/

subject :

Here you are n An integer array of elements nums And an integer k .

Please find the largest average and The length is k A continuous subarray of , And output the maximum average .

Any error less than 10-5 All answers will be considered correct .

Example 1:

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


Example 2:

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

Tips :

n == nums.length
1 <= k <= n <= 105
-10^4 <= nums[i] <= 10^4

source : Power button (LeetCode)
link :https://leetcode-cn.com/problems/maximum-average-subarray-i
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .

Ideas :

continuity k Traversal of numbers , hold k The number is regarded as one , It's like a window , Move back one by one

Record the value of the current window every time you move

  First record the first group k value , Then move

new k The value is equal to The old value - The old first element + New elements

Method 1 、 The sliding window

#define mymax(a,b) ( (a) > (b) ? (a) : (b) )

double findMaxAverage(int* nums, int numsSize, int k){
	int i;
	int sum = 0;
	double max = 0;
	
	for(i=0; i<k; i++)
		sum += nums[i];
	
	max = sum;
	
	for(i=k; i<numsSize; i++)
	{
		sum = sum - nums[i-k] + nums[i];
		max = mymax(max, sum);
	}
	
	return max/k;
}

See more brush notes

原网站

版权声明
本文为[mrbone9]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160012516568.html