πŸ“ Problem Details

πŸ’­What Were My Initial Thoughts?

- cant sort it since the subarray needs to be contiguous 
- having a fixed size sliding window of size k would allow us to traverse and calculate averages for elements in a contiguous subarray

πŸ€”What Did I Struggle With?

~

πŸ’‘ Explanation of Solution

same as initial thoughts ^

βŒ› Complexity Analysis

Time Complexity: O(n)
Space Complexity: O(1)

πŸ’» Implementation of Solution

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        int window_sum = 0;
 
        // Compute the sum of the first window
        for (int i = 0; i < k; ++i) {
            window_sum += nums[i];
        }
 
        // Initialize max average with the first window's average
        double maxAverage = static_cast<double>(window_sum) / k;
 
        // Slide the window across the array
        for (int i = k; i < nums.size(); ++i) {
            window_sum += nums[i] - nums[i - k]; // Update the window sum
            maxAverage = max(maxAverage, static_cast<double>(window_sum) / k); // Update max average
        }
 
        return maxAverage;
    }
};