LeetCode 643: Maximum Average Subarray I Solution
Master LeetCode problem 643 (Maximum Average Subarray I), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
643. Maximum Average Subarray I
Problem Explanation
Explanation:
To solve this problem, we can use a sliding window technique. We will initially calculate the sum of the first k elements in the array. Then, we will slide the window to the right by adding the next element and removing the leftmost element from the window. We will keep track of the maximum average we have seen so far. By updating the sum and recalculating the average at each step, we can find the maximum average subarray of length k.
- Initialize a variable
sumto store the sum of the firstkelements. - Iterate through the array from index
kto the end. - At each step, update the sum by adding the current element and subtracting the element
ksteps back. - Calculate the average by dividing the sum by
kand update the maximum average if needed.
Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(1)
Solution Code
class Solution {
public double findMaxAverage(int[] nums, int k) {
int sum = 0;
for (int i = 0; i < k; i++) {
sum += nums[i];
}
double maxAverage = (double) sum / k;
for (int i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k];
maxAverage = Math.max(maxAverage, (double) sum / k);
}
return maxAverage;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 643 (Maximum Average Subarray I)?
This page provides optimized solutions for LeetCode problem 643 (Maximum Average Subarray I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 643 (Maximum Average Subarray I)?
The time complexity for LeetCode 643 (Maximum Average Subarray I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 643 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 643 in Java, C++, or Python.