Algorithm
Problem Name: 643. 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
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int sum = 0, maxSum;
for(int i = 0; i < nums.size(); i++){
sum += nums[i];
if(i == k - 1) maxSum = sum;
if(i >= k){
sum -= nums[i - k];
maxSum = max(maxSum, sum);
}
}
return (double)maxSum / k;
}
};
Copy The Code &
Try With Live Editor
Input
Output
#2 Code Example with Java Programming
Code -
Java Programming
class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
double maxAverage = sum / k;
for (int i = k; i < nums.length; i++) {
sum -= nums[i - k];
sum += nums[i];
maxAverage = Math.max(maxAverage, sum / k);
}
return maxAverage;
}
}
Copy The Code &
Try With Live Editor
Input
Output
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const findMaxAverage = function(nums, k) {
let max = 0;
let temp = 0;
for(let i = 0; i < k; i++) {
max += nums[i];
}
temp = max;
for(let i = k; i < nums.length ; i++) {
temp = temp - nums[i - k] + nums[i];
max = Math.max(max, temp);
}
return max/k;
};
Copy The Code &
Try With Live Editor
Input
Output
#4 Code Example with Python Programming
Code -
Python Programming
class Solution:
def findMaxAverage(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: float
"""
sm=sum(nums[:k])
mx,j=sm/k, 0
for i in range(k,len(nums)): sm+=nums[i]; sm-=nums[j]; curr=sm/k; mx=max(curr,mx); j+=1
return mx
Copy The Code &
Try With Live Editor
Input
Output
#5 Code Example with C# Programming
Code -
C# Programming
namespace LeetCode
{
public class _0643_MaximumAverageSubarrayI
{
public double FindMaxAverage(int[] nums, int k)
{
var sum = 0;
for (int i = 0; i < k; i++)
sum += nums[i];
double max = (double)sum / k;
for (int i = k; i < nums.Length; i++)
{
sum = sum + nums[i] - nums[i - k];
var average = (double)sum / k;
if (average > max)
max = average;
}
return max;
}
}
}
Copy The Code &
Try With Live Editor
Input
Output