songyy5517 / DataStructures-Algorithms

0 stars 0 forks source link

643. Maximum Average Subarray I #92

Open songyy5517 opened 2 months ago

songyy5517 commented 2 months ago

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

Intuition This problem is to find a contiguous subarray in a array. A striaghtforward idea is to iterate over the array with a sliding window. For each step, calculate the sum of the current window and compare it with the max value, then move the window to the next step.

songyy5517 commented 2 months ago

Approach: Sliding Window

  1. Exception Handling;
  2. Define variables & initiation;
    • sum = nums[0:k-1]: the sum of the current window;
    • max = sum: record the global max sum.
  3. Loop through the array from index k:
    • Calculate the sum of the current window and compare it with the max sum;
  4. Return the max average max * 1.0 / k.

Complexity Analysis

songyy5517 commented 2 months ago
class Solution {
    public double findMaxAverage(int[] nums, int k) {
        // Intuition: Double pointers & Sliding window
        // 1. Exception handling
        if (nums == null || nums.length < k)
            return 0;

        // 2. Initiate sum
        int sum = 0;
        for (int i = 0; i < k; i++)
            sum += nums[i];
        int max_sum = sum;

        // 3. Loop though with sliding window
        for (int i = k; i < nums.length; i++){
            sum = sum + nums[i] - nums[i - k];
            max_sum = Math.max(max_sum, sum);
        }

        return max_sum * 1.0 / k ;
    }
}
songyy5517 commented 2 months ago

2024/5/13