643. Maximum Average Subarray I

ArraySliding Window

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 sum to store the sum of the first k elements.
  • Iterate through the array from index k to the end.
  • At each step, update the sum by adding the current element and subtracting the element k steps back.
  • Calculate the average by dividing the sum by k and update the maximum average if needed.

Time Complexity: O(n), where n is the number of elements in the array. Space Complexity: O(1)

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.