643. Maximum Average Subarray I LeetCode Solution
In this guide, you will get 643. Maximum Average Subarray I LeetCode Solution with the best time and space complexity. The solution to Maximum Average Subarray I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Maximum Average Subarray I solution in C++
- Maximum Average Subarray I solution in Java
- Maximum Average Subarray I solution in Python
- Additional Resources
Problem Statement of 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
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
643. Maximum Average Subarray I LeetCode Solution in C++
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
double sum = accumulate(nums.begin(), nums.begin() + k, 0);
double ans = sum;
for (int i = k; i < nums.size(); ++i) {
sum += nums[i] - nums[i - k];
ans = max(ans, sum);
}
return ans / k;
}
};
/* code provided by PROGIEZ */
643. Maximum Average Subarray I LeetCode Solution in Java
class Solution {
public double findMaxAverage(int[] nums, int k) {
double sum = 0;
for (int i = 0; i < k; ++i)
sum += nums[i];
double ans = sum;
for (int i = k; i < nums.length; ++i) {
sum += nums[i] - nums[i - k];
ans = Math.max(ans, sum);
}
return ans / k;
}
}
// code provided by PROGIEZ
643. Maximum Average Subarray I LeetCode Solution in Python
class Solution:
def findMaxAverage(self, nums: list[int], k: int) -> float:
summ = sum(nums[:k])
ans = summ
for i in range(k, len(nums)):
summ += nums[i] - nums[i - k]
ans = max(ans, summ)
return ans / k
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.