Loading

LeetCode problem#643

Maximum Average Subarray I

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

21 lines
1class Solution {
2    public double findMaxAverage(int[] nums, int k) {
3        int sum = 0;
4        for (int i = 0; i < k; i++) {
5            sum += nums[i];
6        }
7
8        int maxSum = sum;
9        for (int i = k; i < nums.length; i++) {
10            // slide the window
11            sum -= nums[i - k];
12            sum += nums[i];
13
14            if (sum > maxSum) {
15                maxSum = sum;
16            }
17        }
18
19        return (double) maxSum / k;
20    }
21}

How it works

The provided code is a solution for a specific problem on Leetcode, which is to find the maximum average of any contiguous subarray of length k from a given integer array nums. Let's break it down step-by-step.

Problem Breakdown

  1. Inputs:

    • An integer array nums of size n.
    • An integer k, representing the fixed length of the subarrays we will be considering.
  2. Output:

    • The maximum average of any contiguous subarray of length k.

Approach

The solution uses a sliding window technique to efficiently compute the sum of elements in contiguous subarrays of size k without having to recalculate the sum from scratch for each subarray. Here’s how it works:

  1. Initial Sum Calculation:

    • We start by calculating the sum of the first k elements in the array. This sum is stored in the variable sum and also used to initialize maxSum, which will keep track of the maximum sum found.
    1int sum = 0;
    2for (int i = 0; i < k; i++) {
    3    sum += nums[i];  // Calculate the sum of the first k elements
    4}
    5int maxSum = sum;  // Initialize maximum sum to the initial sum
  2. Sliding Window:

    • After computing the initial sum, we proceed to slide the window across the rest of the array. The idea behind sliding the window is that when moving from one subarray to the next, we can subtract the element that is leaving the window (the leftmost element of the current subarray) and add the new element that is entering the window (the next element in the array).
    1for (int i = k; i < nums.length; i++) {
    2    // Slide the window: subtract the element that is leaving the window
    3    // and add the element that is entering the window
    4    sum -= nums[i - k];  // Remove the element going out of the window
    5    sum += nums[i];      // Add the new element in the window
    6    
    7    // Update maxSum if the current sum is greater
    8    if (sum > maxSum) {
    9        maxSum = sum;  // Found a new maximum sum
    10    }
    11}
  3. Calculate Average:

    • After we finish sliding the window through the array, we have found the maximum sum of any contiguous subarray of length k. We can then compute the average by dividing maxSum by k.
    return (double) maxSum / k;  // Return the maximum average

Complexity Analysis

  • Time Complexity: O(n) where n is the number of elements in nums. The algorithm processes each element of the array exactly once.
  • Space Complexity: O(1) since we are using a fixed amount of additional space for the variables.

Conclusion

This solution efficiently finds the maximum average of any contiguous subarray of size k using the sliding window technique, ensuring optimal performance. By maintaining a running sum for the current window and adjusting it as the window moves, we avoid unnecessary recomputation and keep the operation linear in time complexity.

Written by AI from the code above, so double-check anything important.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.